cytsunny
cytsunny

Reputation: 5030

Is there a way to compress image to be below a certain file size limit?

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?

Upvotes: 1

Views: 1111

Answers (2)

Uwe Ohse
Uwe Ohse

Reputation: 1

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.

Upvotes: 0

Leif
Leif

Reputation: 2170

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.

Upvotes: 0

Related Questions