How to resize image by imagine extension in yii2

11,440

Solution 1

Use resize method as below

 use yii\imagine\Image;  
 use Imagine\Image\Box;  

 public function upload() {
        $this->pictureFile->saveAs('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);

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

Solution 2

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.

Solution 3

    Yii::setAlias('newsfolder', dirname(dirname(__DIR__)) . '/frontend/web/extraimages/');

    $model->img = UploadedFile::getInstance($model,'img');
    if (!empty($model->img)){
        $model->img->saveAs( Yii::getAlias('@newsfolder/').$filename.'.'.$model->img->extension );
        $model->img =  $filename.'.'.$model->img->extension;
        $imagine = Image::getImagine();
        $image = $imagine->open(Yii::getAlias('@newsfolder/'.$model->img));
        $image->resize(new Box(500, 300))->save(Yii::getAlias('@newsfolder/'.$model->img, ['quality' => 70]));
    }
Share:
11,440
Mohammad Aghayari
Author by

Mohammad Aghayari

Updated on June 11, 2022

Comments

  • Mohammad Aghayari
    Mohammad Aghayari almost 2 years

    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);
            }
    
  • Mohammad Aghayari
    Mohammad Aghayari about 8 years
    could you please vote may question? I'm question ban :-(