Scale image according a maximum file size

半城伤御伤魂 提交于 2019-11-29 16:44:07

The extent function you're calling is just to set the size of an image.

The function to set the jpeg extent option is:

$imagick->setOption('jpeg:extent', '2500kb');

Interestingly, the function $imagick->getImageBlob() seems to crash after setting this option. You are forced to write the file to disk, rather than being able to get it's bytes directly.

The output format is always JPEG so if there is a way to calculate the size before to save it that would be great

There isn't. The amount of detail that is in each image determines what size the image will be after compression, for a given image quality. So it's not possible to calculate the quality level that will give a final size.

The C code from the underlying Image Magick library that limits the file size is:

maximum=101;
for (minimum=2; minimum < maximum; )
{
    jpeg_image->quality=minimum+(maximum-minimum+1)/2;
    status=WriteJPEGImage(jpeg_info,jpeg_image);
    if (GetBlobSize(jpeg_image) <= extent)
      minimum=jpeg_image->quality+1;
    else
      maximum=jpeg_image->quality-1;
    }
}

I.e. it just recompresses the file at different image quality levels, until it finds the level that gives the acceptable file size for the given value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!