How to compress an image to 200Kb using PHP

648 Views Asked by At

In my yii2 project, I have image compression code. I want to compress images of any size to 200kb. I am using Yii2 imagine extension for compressing the image. My code is

Image::thumbnail($uploadPath . '/' . $file->name,$newwidth, $newheight)
     ->save($uploadPath . '/' . $file->name,['quality' => 100]); 

$newwidth and $newheight are the original width and height of images we are uploading. The compression is working fine. But it compressing the maximum. Suppose I uploaded a 1MB picture ,then the output image size will be like 30kb, I mean too small. So what I need is, I have to compress to 200Kb. So if any size, the output should be 200kb.

Is there any way to do that?? If we have any options with the core php also please let me know.

1

There are 1 best solutions below

1
coaelecsoft On

Try this extension: https://github.com/yiisoft/yii2-imagine

I am useing next code:

Image::getImagine()->open($originFile)
   ->thumbnail(new Box(800, 800))
   ->save($filesPath .'/'. $newImageName . '.' . $originFile->file->extension, ['quality' => 100]);

You must include in controller next:

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