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

12 followers

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

Total 3 comments

#20126 report it
Superwow at 2017/09/12 10:33am
For docker
RUN apt-get update && apt-get install -y \
            libfreetype6-dev \
            libjpeg62-turbo-dev \
            libmcrypt-dev \
            libpng12-dev \
        && docker-php-ext-install -j$(nproc) iconv mcrypt \
        && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
        && docker-php-ext-install -j$(nproc) gd
#20081 report it
Yair at 2017/05/20 02:29pm
gmagick and imagick

To save someone a little time:

The library tries to load:

1. gmagick
2. imagick
3. GD

by this order. See vendor\yiisoft\yii2-imagine\BaseImage.php in createImagine()

So no need to have a special use statement like use Imagine\Gd;

#19842 report it
Nabi at 2016/04/28 12:33pm
bug in your sample codes

Thanks. In your sample code "crop()" method need 2 arguments for width and heighr. and "use Imagine\Image\BoxInterface;" dont needed.

Leave a comment

Please to leave your comment.

Write new article