Yii2 Create Image Thumbnails

Yii2 Create Image Thumbnails

  • 08 Sep 2016
  • 10

I hope everyone watched my tutorial on how to upload images in Yii. If you haven't take a look


When you upload a image it is almost all the time necessary to create a thumbnail for that image. This is really easy to do. Yii2 provides a easy to use extension for this. It is developed by the Yii core team so it guarantees its goodness :)

To use the imagine extension you need to first install it so as always lets use composer to do this

copy and paste the below code in your terminal

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

After you install it just use this simple code to create image thumbnails

In the controller where you are uploading the image

// firstly use this so that we can use Image class - add this to the top of of controller

use yii\imagine\Image;

// in the controller action

$itemImage->path = 'web/uploads/imagName.png';

// create a thumbnail with width and height of 120 pixels

Image::thumbnail( $itemImage->path , 120, 120)
           ->save('web/uploads/thumbnail/imageName.png ', ['quality' => 50]);

// if you want to save the image thumbnail path in the db create a column 'thumbnail_path' and assign // the value here

$itemImage->thumbnail_path = 'web/uploads/thumbnail/imageName.png ; 

That is it now your image thumbnail will be saved in web/uploads/thumbnail folder it will have the width and height of 120 pixels if you want to change that obviously change values in the parameters.

f you want to know more about the extension take a look

Hope you got some new knowledge. If you have other requests or problems do drop a comment

Have fun Yii developers.