1

To compress image in PHP, this is one of the way:

<?php 
function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

REFERENCE

However, this is only to compress by specifying a certain quality. Currently I am working on an image upload function. Instead of setting a hard file size limit as usual, I would like to compress the uploaded image that is larger than the file size limit, so that it would be below the file size limit. Is there a way I can do that WITHOUT try and error?

cytsunny
  • 4,838
  • 15
  • 62
  • 129

3 Answers3

1

Yes, you can use http://phpthumb.sourceforge.net/ for this. In the image processing features list it says

  • Quality can be auto-adjusted to fit a certain output byte size.

There is also this https://www.phpclasses.org/package/3810-PHP-Optimize-images-to-fit-in-a-given-file-size-limit.html

ProEvilz
  • 5,310
  • 9
  • 44
  • 74
  • You have my upvote. But internally this tool will most likely use try and error, maybe with a bit more sophisticated method. – Leif Sep 26 '17 at 11:42
  • There aren't many methods available, I figured it was worth a try. – ProEvilz Sep 26 '17 at 11:42
0

No, because none of the jpeg libraries support that kind of feature (jpeg compression is content dependent). You can give them compression parameters (quality, quantification tables), but no compression targets.

The trial and error solution takes far too long for most purposes. Your purpose may be different, though. But if not, and you absolutely need to compress the images below a certain file size, you could try to reuse quality parameters from very similar images (photos shot in the same minute, for example).

Addendum, since i can't add a comment: jpegfit will try to get a perfect match, meaning it will stop after the full number of iterations (16 by default), and phpthumb decreases the quality too strongly (default, 82,70,60,52,46,40,35,30,26,22,...) for my taste.

Uwe Ohse
  • 1
  • 1
0

Instead of setting a hard file size limit as usual, I would like to compress the uploaded image that is larger than the file size limit, so that it would be below the file size limit. Is there a way I can do that WITHOUT try and error?

So you don't necessarily want to compress the file just below the file size limit. And you do not want try and error. The solution is to set quality to 0. If the size is below the limit then, you succeeded. If it is above, then there is no way to get the file below that size.

Leif
  • 2,143
  • 2
  • 15
  • 26