How to resize image by imagine extension in yii2

Viewed 11995

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);
        }
4 Answers
$imagine = Image::getImagine();
        $imagine = $imagine->open($openPath);
        $sizes = getimagesize ( $openPath ); 
        /*                   
           [0] => 604
           [1] => 244
           [2] => 3
           [3] => width="604" height="244"
           [bits] => 8
           [mime] => image/png
        ) */
        $width = 200;
        $height = round($sizes[1]*$width/$sizes[0]);        
        $imagine = $imagine->resize(new Box($width, $height))->save($savePath, ['quality' => 60]); 
Related