Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize image by imagine extension in yii2

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);
        }
like image 480
Mohammad Aghayari Avatar asked Mar 15 '16 09:03

Mohammad Aghayari


3 Answers

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.

like image 139
yetanotherse Avatar answered Nov 19 '22 00:11

yetanotherse


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);
    }
like image 3
ck_arjun Avatar answered Nov 18 '22 23:11

ck_arjun


    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]));
    }
like image 1
Davron Achilov Avatar answered Nov 19 '22 01:11

Davron Achilov