PHP - resize image to a specific (k) size?
January 12, 2006 8:53 AM
Subscribe
Formula to resize an image (in PHP) so that the resulting file is roughly a certain size in bytes?
The task: If a file uploaded through a web form is >50k, scale it down so it's about 50k.
My PHP code for the actual scaling is working fine; what I'm trying to figure out is the best way to calculate the target height and width. (Leaving JPEG quality out of the equation for the time being.) This tends to produce files that are too large:
$pct = ($max_k * 1024) / filesize($file);
list($width_orig, $height_orig) = getimagesize($file);
$height = $height_orig * $pct;
$width = $width_orig * $pct;
I think I need to somehow either adjust the percentage based on the proportion between the two dimensions, or multiply the area by the percentage to get a desired area and then do something with that, but what? Square roots?
Or is it going to come out inaccurately whatever I do because there's so much variation among individual images?
Any suggestions appreciated.
posted by staggernation to computers & internet (8 comments total)
There's your problem right there. JPG images can compress really, really well, or really really poorly... Your best bet, though it's somewhat system intensive, is a bit of "trial and error"... perhaps have 2 or 3 preset sizes to size down to, and automatically choose the one that is of optimal filesize using some formula.
Also, I know that many times programmers hate using external tools, but might I suggest ImageMagick? It will allow you to save at one fixed size, but varying levels of quality (or maybe php lets you do this natively? I dunno) so that you can choose the best image...
posted by twiggy at 8:55 AM on January 12, 2006