How to use imagine ( crop, thumb, effects for images ) on Yii2

  1. Installation
  2. Examples of use
  3. Resources

Imagine adds most common image functions and also acts as a wrapper to Imagine image manipulation library.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-imagine "*"

or add

"yiisoft/yii2-imagine": "*"

to the require section of your composer.json and run:

php composer.phar update

Examples of use

To try this examples please place any photo in web/img/test-photo.jpg and see the result on runtime folder.

Crop
use yii\imagine\Image;

Image::crop(Yii::getAlias('@webroot/img/text-photo.jpg'))
->save(Yii::getAlias('@runtime/crop-photo.jpg'), ['quality' => 80]);
Thumbnail
use yii\imagine\Image;

Image::thumbnail('@webroot/img/test-photo.jpg', 120, 120)
    ->save(Yii::getAlias('@runtime/thumb-test-photo.jpg'), ['quality' => 80]);
Resizing and Preserving Aspect Ratio
use yii\imagine\Image;
use Imagine\Gd;
use Imagine\Image\Box;
use Imagine\Image\BoxInterface;

Image::getImagine()->open($fileName)->thumbnail(new Box($newWidth, $newHeight))->save($savePath , ['quality' => 90]);



Effects

More effects

Grayscale
use yii\imagine\Image;

$image = yii\imagine\Image::getImagine();
$newImage = $image->open(Yii::getAlias('@webroot/img/test-photo.jpg'));

$newImage->effects()->grayscale();

$newImage->save(Yii::getAlias('@runtime/grayscale-test-photo.jpg'), ['quality' => 80]);
Blur

Required Imagick or Gmagick php extension

use yii\imagine\Image;

$image = yii\imagine\Image::getImagine();
$newImage = $image->open(Yii::getAlias('@webroot/img/test-photo.jpg'));

$newImage->effects()->blur(3);

$newImage->save(Yii::getAlias('@runtime/blur-test-photo.jpg'), ['quality' => 80]);

Resources