Search code examples
phpimage-optimization

Resize an image and maintain quality?


I have a problem with resizing images.

What happens is that if you upload a file larger than the stated parameters, the image is cropped, then saved at 100% quality.

So if I upload a large jpeg which is 272Kb. The image is cropped by 100 odd pixels. The file size then goes up to 1.2Mb.

We are saving images at a 100% quality. I assume that this is what is causing the problem. The image is exported from Photoshop at 30% quality which reduces the file size. Resaving the image at 100% quality creates the same image but I assume with a lot of redundant file data.

Has anyone encountered this before? Does anyone have a solution?

This is what we are using.

$source_im = imagecreatefromjpeg ($file);
$dest_im = imagecreatetruecolor ($newsize_x, $newsize_y);
imagecopyresampled (
    $dest_im, $source_im,
    0, 0,
    $offset_x, $offset_y,
    $newsize_x, $newsize_y,
    $sourceWidth, $sourceHeight
);

imagedestroy ($source_im);
if ($greyscale) {
    $dest_im = $this->imageconvertgreyscale ($dest_im);
}
imagejpeg($dest_im, $save_to_file, $quality);
break;

Solution

  • Saving at 30% then re-saving at 100% will, as you say, create redundant data, whether you crop, resize, whatever.

    Unfortunately, JPEG compression accumulates data loss, so compressing at 30%, processing the image, then re-compressing will always look worse than the original compression. The rule of thumb is to avoid compression (especially heavy compression like 30%) until as late in the process as possible. So upload at 100% (or 80ish% if necessary), then compress.

    Edit: apparently, jpegtran (google it) can do operations such as cropping without first decompressing the image, as long as the image size follows certain constraints (usually width and height a multiple of 16 pixels). Haven't tried it myself, but it might suite your purposes.