Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

php - Scale image according a maximum file size

I'm using Imagick and like to scale an image to a maximum file size of 2.5MB

I had a look to this SOF question: ImageMagick: scale JPEG image with a maximum file-size which is exactly what I want to do but the extent() method from Imagick does not have the size parameter: http://www.php.net/manual/en/imagick.extentimage.php

Anyone knows how I could to it? At the moment I'm trying to calculate a coefficient between the original file size and the target file size to calculate a new resolution but found out that the resolution is not proportional to the file size.

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

Thanks in advance, Maxime

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...