Image manager extension for the Yii PHP framework.

Overview

yii-imagemanager

Latest Stable Version Build Status

Image manager extension for the Yii PHP framework.

Introduction

I started this project to reduce the need for boilerplate code when working with images in my Yii applications. The goal was not to provide an user interface for image management but to wrap the powerful Imagine library using Yii's conventions. Imagine is one of the best image manipulation libraries for PHP and comes with a wide range of different image filters and supports all the major graphics libraries.

This extension is an extension to my yii-filemanager extension.

Features

  • A wide range of image filters such as crop, resize and thumbnail
  • Image presets with support for caching of generated images
  • Support for both server and client -side (through holder.js) placeholders
  • Storing of uploaded images in the database
  • Supports multiple graphics libraries including GD, Imagick and Gmagick
  • Application component that provides centralized access
  • Active record behavior to ease working with the API

Setup

The easiest way to get started with the yii-imagemanager is to install it using Composer. That way Composer will take care of installing its dependancies, the yii-filemanager and Imagine. Alternatively you can download the extension and it's dependencies manually. Just make sure that all the libraries are registered with the autoloader.

Add the following rows your composer.json file:

"require": {
  .....
  "crisu83/yii-imagemanager": "dev-master"
},
"minimum-stability": "dev",

Run the following command in the root directory of your project:

php composer.phar install

Add the image manager application component to your application configuration:

'components' => array(
  .....
  'imageManager' => array(
    'class' => 'vendor.crisu83.yii-imagemanager.components.ImageManager',
    'presets' => array(
      'myPreset' => array(
        'filters' => array(
          array('thumbnail', 'width' => 160, 'height' => 90, 'mode' => 'outbound'),
        ),
      ),
    ),
    'holders' => array(
      'default' => 'placeholder.png',
    ),
  ),
),

The following configuration parameters are available for the image manager:

  • driver the image driver to use, valid drivers are gd, imagick and gmagick
  • presets the preset filter configurations (name => config)
  • holders the placeholder image configurations (name => filename)
  • imageDir the name of the images directory
  • rawDir the name of the directory with the unmodified images
  • cacheDir the name of the direcotry with the cached images
  • holderDir the name of the directory with placeholder images
  • clientHolderText the text used with client-side placeholders
  • modelClass the name of the image model class
  • dependencies the map over dependency paths (name => path)
  • filterManagerID the component ID for the file manager component

Add the image command to your console application configuration:

'commandMap' => array(
  .....
  'image' => array(
    'class' => 'vendor.crisu83.yii-imagemanager.commands.ImageCommand',
  ),
),

Run the following command through yiic:

" --path=""">
yiic image createAccessFile --baseUrl="" --path=""

The following arguments are available for the createAccessFile action:

  • baseUrl the rewrite base url to use
  • path the full path to the access file to create

What's included?

  • ImageBehavior behavior that ease saving, rendering and deleting of images associated with active records
  • ImageCommand console command for running shell tasks
  • ImageManager application component that provides centralized access
  • ImagePreset component that defines a single image preset
  • ImageController controller for running actions via an URL
  • ImagineFilter the base class for all the image filters
  • Image model class for the image table

Getting started

Once your have configured everything you are ready to start using the image manager. Below I will try to explain the most basic features and how to use them.

Configure presets and placeholders

We need to add a few more things to your application configuration before we can begin. In this example we will add a preset and a placeholder image to the image manager. Add the following lines to your application configuration:

  'imageManager' => array(
    .....
    'presets' => array(
      'product' => array(
        'filters' => array(
          array('thumbnail', 'width' => 220, 'height' => 220, 'mode' => 'outbound'),
        ),
      ),
    ),
    'holders' => array(
      'default' => 'placeholder.png', // you need to add an image named placeholder.png in the images/holder directory for this
    ),
  ),

Attach the image behavior to your model

Let us assume that you have a model called Product for which you want to upload images. In order to do so we need to add an imageId column to your user table where we can store the id for the associated image model. To attach the behavior we add the following code to the Product class:

/**
 * .....
 * Methods accessible through the 'ImageBehavior' class:
 * @method CUploadedFile getUploadedImage()
 * @method Image saveImage($file, $name = null, $path = null, $scenario = 'insert')
 * @method string renderImagePreset($name, $alt = '', $htmlOptions = array(), $holder = null)
 * @method string createImagePresetUrl($name, $holder = null)
 * @method boolean deleteImage()
 */
class Product extends CActiveRecord
{
  /**
   * @var CUploadedFile the uploaded file (used when uploading a product image).
   */
  public $upload;
  
  /**
   * @return array the behavior configurations (behavior name=>behavior config).
   */
  public function behaviors()
  {
    return array(
      'image' => array(
        'class' => 'vendor.crisu83.yii-imagemanager.behaviors.ImageBehavior',
        'name' => $this->name,
        'path' => 'products',
      ),
    );
  }
  
  /**
   * @return array relational rules.
   */
  public function relations()
  {
    return array(
      'image' => array(self::BELONGS_TO, 'Image', 'imageId'),
    );
  }
  
  /**
   * @return array validation rules for model attributes.
   */
  public function rules()
  {
    return array(
      ......
      array('upload', 'file'), // configure the validator if necessary
    );
  }
  
  /**
   * @return array customized attribute labels (name=>label).
   */
  public function attributeLabels()
  {
    return array(
      'upload' => 'Image',
    );
  }
  
  .....
}

Uploading and saving the image

Alright, now we can save images through the Product model. Next we will add an action that renders a view that contains a form with a file input. When the form is submitted the uploaded image should be saved in the database. Here is the code for both the action and the view:

class ProductController extends Controller
{
  .....

  /**
   * Displays the page for editing the details for a specific product.
   */
  public function actionUpdate($id)
  {
    $model = Product::model()->findByPk($id);
    if (isset($_POST['Product']) {
      $model->attributes = $_POST['Product'];
      if ($model->save()) {
        $this->redirect(array('admin'));
      }
    }
    $this->render('update', array('model' => $model);
  }
}
beginWidget('CActiveForm', array( 'htmlOptions' => array('enctype' => 'multipart/form-data'), // don't forget this! )); ?> ..... labelEx($model, 'uploadedFile'); ?> fileField($model, 'uploadedFile'); ?> error($model, 'uploadedFile'); ?>
renderImagePreset('product', $model->name, array(), 'default'); ?>
endWidget(); ?>
">

/* @var ProductController $this */
/* @var Product $model */
/* @var CActiveForm $form */
?>
<div class="product-controller update-action">
   $this->beginWidget('CActiveForm', array(
    'htmlOptions' => array('enctype' => 'multipart/form-data'), // don't forget this!
  )); ?>
  
    .....
  
     echo $form->labelEx($model, 'uploadedFile'); ?>
     echo $form->fileField($model, 'uploadedFile'); ?>
     echo $form->error($model, 'uploadedFile'); ?>
    
    <div class="product-image">
       echo $model->renderImagePreset('product', $model->name, array(), 'default'); ?>
    div>
    
     echo CHtml::submitButton(); ?>
  
   $this->endWidget(); ?>
div>

There's more

This is just scratching the surface of what you can do with this extension, there are a lot of filters to explore and you can also work with the image manager API directly without the image behavior if you desire. The best way to learn to use this extension is to read through its code, especially the ImageManager application component. Good luck!

Comments
  • createAccessFile

    createAccessFile

    Could somebody explain what this line from the docs actually does?

    ..... yiic image createAccessFile --baseUrl="<base/url>" --path="<path/to/images>"

    (then I might know what do to with it....) Sorry, but I am a beginner..

    gb5256

    question 
    opened by gb5256 4
  • Error composer

    Error composer

    Hi, sorry for my bad english. I added the line of composer: "crisu83/yii-imagemanager": "dev-master" I get this error:

    Loading composer repositories with package information Installing dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

    Problem 1 - Installation request for crisu83/yii-imagemanager 1.0.0 -> satisfiable by crisu83/yii-imagemanager[1.0.0]. - Can only install one of: crisu83/yii-imagemanager[dev-master, 1.0.0]. - Installation request for crisu83/yii-imagemanager dev-master -> satisfiable by crisu83/yii-imagemanager[dev-master].

    thanks

    opened by kodemo 3
  • Different names for the same parameter

    Different names for the same parameter

    In the (last) rewrite rule (which redirects to the 'preset' action) from the generated .htaccess file (line 73 in commands/ImageCommand.php) the second parameter is named 'id', while the corresponding function in the controller has the second parameter named 'fileId' (line 37 in controllers/ImageController.php). In result action is not triggered and the image is not displayed.

    opened by vundicind 1
  • Remove import of AjaxResponse component

    Remove import of AjaxResponse component

    It is no longer possible to automatically import the AjaxResponse component, as the image manager does not have dependencies anymore. We must rely on the application to import the component. The Crisu83/yii-ajaxtools package, where AjaxResponse is located, could use composer's autoloading to make this easier.

    opened by kryysler 1
  • ImageBehavior event handler methods should be public (not protected as in

    ImageBehavior event handler methods should be public (not protected as in

    I tried to use yii-imagemanager, installed by doc, view sources, but events in ImageBehavior.php had't been called. Then i read phpDoc in the parent class CActiveRecordBehavior and there was declared:

    "Override this method and make it public if you want to handle the corresponding event of the owner"

    So i changed all protected event handlers in ImageBehavior to public, and the behavior actually started working. I tested with Yii 1.1.14

    So @Crisu83 , can you please check it, may be it's all correct in your src. Thanks

    bug 
    opened by mentecuantica 1
  • Allow for preset filters to change without having to clear the cache

    Allow for preset filters to change without having to clear the cache

    By including the filters in the cache checksum, it is possible to change them afterwards without having to remove the existing cached images. This also enables the use of dynamic preset filters with the same name.

    opened by kryysler 0
  • Typo in sprintf

    Typo in sprintf

    in yii-imagemanager/components/ImageManager.php, line 410: throw new CException(sprintf('Failed to locate image model with id "%d".'), $id); fails, as the $id paramter is not given to sprintf, but to CException.

    opened by soderluk 0
  • Is having autoSave on by default in ImageBehavior really desirable?

    Is having autoSave on by default in ImageBehavior really desirable?

    When the autoSave is on you cannot save the owner without having the uploaded file. This means that updating any other field in the owner requires a new file to be uploaded to work.

    question 
    opened by kryysler 1
Owner
Christoffer Niska
Technical Lead at Tesseract, father of many, polyglot programmer, open source enthusiast, TypeScript Ninja.
Christoffer Niska
Auto Image & file upload, resize and crop for Laravel eloquent model using Intervention image

Laravel ImageUp The qcod/laravel-imageup is a trait which gives you auto upload, resize and crop for image feature with tons of customization. Install

QCode.in 708 Dec 22, 2022
A Laravel Gravatar package for retrieving gravatar image URLs or checking the existance of an image.

Gravatar for Laravel 5.x, 6, 7 and 8 Installation First, pull in the package through Composer via the command line: composer require creativeorange/gr

Creativeorange 477 Dec 1, 2022
This plugin adds a new image style for the Core Image block.

This plugin adds a new image style for the Core Image block. Introduction How to use? Go to Gutenberg Editor and add a image block. e.g. Add new image

Mahesh Waghmare 3 Feb 17, 2022
PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options !

PHP Image Editor PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options ! ✨ Supporting ⭐ Star this repos

Franck Alary 17 Nov 13, 2022
This is an image manipulation REST API written in PHP Laravel Framework

Laravel Image Manipulation REST API Demo Here is fully working Demo: https://www.lobiimages.com/ You have to register first in order to generate acces

TheCodeholic 42 Dec 15, 2022
Image Resize Middleware for Slim Framework

Image Resize Middleware for Slim This middleware implements automatic image resizing based on image filename. Install You can install latest version u

Mika Tuupola 61 Apr 12, 2022
PHP Image Manipulation

Intervention Image Intervention Image is a PHP image handling and manipulation library providing an easier and expressive way to create, edit, and com

null 13k Jan 3, 2023
PHP 5.3 Object Oriented image manipulation library

Imagine Tweet about it using the #php_imagine hashtag. Image manipulation library for PHP 5.3 inspired by Python's PIL and other image libraries. Requ

Bulat Shakirzyanov 4.3k Jan 6, 2023
🌄 Perceptual image hashing for PHP

ImageHash A perceptual hash is a fingerprint of a multimedia file derived from various features from its content. Unlike cryptographic hash functions

Jens Segers 1.9k Dec 28, 2022
php-gd based image templates

gdaisy A highly experimental image templating system based on PHP-GD to dynamically generate image banners and covers. Installation 1. Require erikahe

Erika Heidi 67 Nov 22, 2022
Grabs the dominant color or a representative color palette from an image. Uses PHP and GD, Imagick or Gmagick.

Color Thief PHP A PHP class for grabbing the color palette from an image. Uses PHP and GD or Imagick libraries to make it happen. It's a PHP port of t

Kevin Subileau 610 Dec 28, 2022
image sharing site made in PHP just for fun and freetime

2bart image sharing site made in PHP just for fun and freetime To-do list: upload system [DONE] ✔️ views system [DONE] ✔️ image list system [DONE] ✔️

goom 1 Oct 22, 2021
PHP Thumb is a light-weight image manipulation library aimed at thumbnail generation

PHP Thumb NOTICE - This project was recently updated to 2.0 and is PSR-0 compliant and supports Composer integration. Some parts of the documentation

Ian Selby 985 Dec 4, 2022
Wonderfully easy on-demand image manipulation library with an HTTP based API.

Glide Glide is a wonderfully easy on-demand image manipulation library written in PHP. Its straightforward API is exposed via HTTP, similar to cloud i

The League of Extraordinary Packages 2.4k Dec 19, 2022
Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim and jpegtran tools.

Image Optimizer This library is handy and very easy to use optimizer for image files. It uses optipng, pngquant, jpegoptim, svgo and few more librarie

Piotr Śliwa 879 Dec 30, 2022
:racehorse: find the size of an image without downloading the whole file. Supports batch requests.

FasterImage FasterImage finds the dimensions or filetype of a remote image file given its uri by fetching as little as needed, based on the excellent

Will Washburn 58 Nov 30, 2022
Extract colors from an image like a human would do.

ColorExtractor Extract colors from an image like a human would do. Install Via Composer $ composer require league/color-extractor:0.3.* Usage require

The League of Extraordinary Packages 1.2k Jan 1, 2023
An open source image hosting service powered by Laravel

Limg An open source image hosting service powered by Laravel Features Upload your image via file, url or ShareX ! Manage your image (custom title, pub

Thomas 56 Dec 16, 2022
A simple page view counter that store data as text and shows data as a PNG image

Image Counter A simple page view counter that store data as text and shows the counter as a PNG image.

Victor Ribeiro 10 Apr 19, 2022