php resize image without loss quality

giozh picture giozh · Feb 26, 2015 · Viewed 20k times · Source

i've implement this method (by following php tutorial) for create preview of an images:

function createPreview($image_path, $filename) {

    header('Content-Type: image/jpeg');
    $thumb = imagecreatetruecolor(350, 350);
    $source = imagecreatefromjpeg($image_path);

    list($width, $height) = getimagesize($image_path);

    imagecopyresized($thumb, $source, 0, 0, 0, 0, 350, 350, $width, $height);

    imagejpeg($thumb, $filename."_prev.jpg");
}

but i've noticed that scaled image loss a lot of quality. How can i preserve quality of scaled image (i can't use imagick, my server doesn't support it)

Answer

sectus picture sectus · Feb 26, 2015

imagejpeg uses 75 quality by default. So you need to define it explicitly.

imagejpeg($thumb, $filename."_prev.jpg", 100);

Also, use imagecopyresampled

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.