I have to upload image files that meet a max width dimension and max file size.
I have the code that checks width size and resizes the image to meet the max image w
Here is a way to achieve that. It does not save a file until it is satisfied that the file size will be lower than the specified maximum.
$original_file = 'original.jpg';
$resized_file = 'resized.jpg';
$max_file_size = '30000'; // maximum file size, in bytes
$original_image = imagecreatefromjpeg($original_file);
$image_quality = 100;
do {
$temp_stream = fopen('php://temp', 'w+');
$saved = imagejpeg($original_image, $temp_stream, $image_quality--);
rewind($temp_stream);
$fstat = fstat($temp_stream);
fclose($temp_stream);
$file_size = $fstat['size'];
}
while (($file_size > $max_file_size) && ($image_quality >= 0));
if (-1 == $image_quality) {
echo "Unable to get the file that small. Best I could do was $file_size bytes at image quality 0.\n";
}
else {
echo "Successfully resized $original_file to $file_size bytes using image quality $image_quality. Resized file saved as $resized_file.\n";
imagejpeg($new_image, $resized_file, $image_quality + 1);
}
This requires no file to be written until you've successfully found the ideal compression ratio.
This loop starts with an $image_quality of 100, then counts downward trying each new value on a temporary in-memory buffer. If gets down to trying 0 and the file would still be too big, it returns an error message. Otherwise, if it gets to a value that works, it reports that and saves the new file using that image quality setting.
If you're feeling adventurous, you could implement a binary search algorithm to find the ideal compression ratio more quickly, but this quick-fix gives the same result, albeit possibly a tad slower.