-1

Im working on an application that allows users to upload images. We are setting a maximum file size of 1MB. I know there are a few options out there for compressing JPEGs (and we are dealing with jpegs here).

From what ive seen, all of these functions just allow you to define a compression ratio and scale it down. Im wondering if there is a function that allows you to define a maximum file size and have it calculate the compression ratio necessary to meet that size.

If not, I was thinking my best approach would be to use a while loop that looks at size and just keep hitting the image with imagejpeg() in 10% increments until the file is below the pre-defined max-size.

Am I on the right track here?

Kirk Logan
  • 733
  • 2
  • 8
  • 23
  • no, there isn't such a function, and what you're suggesting is about the only practical way of doing it. there's no real practical way to predict how well an image will compress. – Marc B Dec 23 '14 at 15:33
  • Different images having the same width and height, saved as JPEG with the same quality have different file size. The file size depends on the image content. An image with many details will compress less than a simple image that contains large smooth surfaces. It's not possible to determine the file size in advance; you need to save the file as JPEG first, then check the file size. – axiac Dec 23 '14 at 15:36
  • Thats what I figured, just thought id ask around. I appreciate the feedback. – Kirk Logan Dec 23 '14 at 15:55

2 Answers2

0

It depends on the data but with images you can take small small samples. Downsampling would change the result. Here is an example:PHP - Compress Image to Meet File Size Limit.

Community
  • 1
  • 1
Micromega
  • 12,486
  • 7
  • 35
  • 72
0

I completed this task using the following code:

$quality = 90;
while(filesize($full_path) > 1048576 && $quality > 20) {
    $img = imagecreatefromjpeg($full_path);
    imagejpeg($img,$full_path,$quality);

    $quality = $quality - 10;
    clearstatcache();
}
if(filesize($full_path) > 1048576) {echo "<p>File too large</p>"; unlink($full_path); exit;}

The $quality > 20 part of the statement is to keep the script from reducing the quality to a point I would consider unreasonable. Im sure there is more to be done here. I could add in a resolution re-size portion as well, but this works for my current needs. This is with a max file size of 1MB. If the file is still too large after maximum quality scale, it returns a file too large error and deletes the image from the server.

Take note that clearstatcache() is very important here. Without this, the server caches the image size and will not notice a change in file size.

This script only applies to JPEGs, but there are other php functions for gifs, pngs, etc.

Kirk Logan
  • 733
  • 2
  • 8
  • 23