How to resize image by imagine extension in yii2

Mohammad Aghayari picture Mohammad Aghayari · Mar 15, 2016 · Viewed 10.2k times · Source

I use the bellow function to resize images after upload to show on my post. but it works just for images larger than 500px 300px. when I upload image smaller than this size, my website images row breaks down.

use yii\imagine\Image;    
public function upload() {
            $this->pictureFile->saveAs('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);

            Image::thumbnail('../files/upload/' . $this->pictureFile, 500, 300)
                    ->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension, 
                            ['quality' => 70]);
            unlink('../files/upload/' . $this->pictureFile->baseName . '.'  . $this->pictureFile->extension);
        }

Answer

yetanotherse picture yetanotherse · Mar 15, 2016

Instead of Image::thumbnail, try the following

$imagine = Image::getImagine();
$image = $imagine->open('../files/upload/' . $this->pictureFile);
$image->resize(new Box(500, 300))->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension, ['quality' => 70]);

Haven't tested it but since yii's Image is just a wrapper over Imagine library, this should work with minor changes (if at all needed).

And yes, you need to use Imagine\Image\Box; in your file before using the code above.