简体   繁体   中英

Using imagejpeg to make image files unnoticeable smaller

I'm making an image sharing website with php. I was reading about google's pagespeed, and they said I needed to optimize my images, so I've been trying to do that with imagejpeg, then hopefully I'll be able to use basically the same code with png and gif.

This is the code I have at the moment:

$img = imagecreatefromjpeg($original);

if ($extension === "jpg" || $extension === "jpeg"){
    $location = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $id . "/fullsize." . $extension;
    $temp = fopen($location, 'w');
    imagejpeg($img, $location, 80);
    fclose($temp);
}

And it does the job of taking the image at $original, and saving a copy that's been through imagejpeg to $location.

But sometimes the resulting file is larger than the original was! This is where I get stumped.

Why is this happening?

How can I make it stop happening?

I'm trying to reduce image file sizes without hurting their appearance, is there a better way to do it than this?

Thanks,

Liam

imagejpeg will only shrink the file if you save it at a lower quality setting than the original was produced with

eg

imagejpeg($gd, 'temp.jpg', 50);
$temp = imagecreatefromjpeg('temp.jpg');
imagejpeg($gd, 'temp2.jpg', 70);

will probably produce a larger temp2 file, because it's at a higher quality setting, which roughly translates to "don't compress as much".

There's no way to predict what the final output size will be for a given image and quality setting without actually going through the whole jpeg compress process. You may have to do a few trial recompresses of an image and lower the quality setting each time until you start getting some shrinkage.

of course, if you lower the quality TOO low, you'll basically trash the image and definitely introduce visible artifacts.

It definitely depends on the quality of the original image. If your image is quality 60 originally, saving at quality 80 will generally result in a larger file size.

However, it also depends on what software created the original image. For example, I've observed many times where Adobe Photoshop can save an image at quality 60 that looks as good as 80 from GD (the graphics library you are using). Also, Photoshop can often save images at the same quality as another graphics package but with a smaller size. This is subjective, of course. I'm not necessarily concluding Photoshop is "better," but it does appear to have it's options well tuned.

I recommend you try ImageMagick, as I've seen it generally do a better job (file sizes, image quality) than GD. You should also determine the original quality setting per image so you don't accidentally grow images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM