You are viewing revision #13 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.
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 ¶
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]);
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.
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;
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
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.