Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php resize image without loss quality

Tags:

php

image

php-gd

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)

like image 953
giozh Avatar asked Feb 26 '15 09:02

giozh


People also ask

How to reduce the size of image in PHP?

If the allowed image type is valid, call another custom function to compress the image size. This function will reduce image size using PHP imagejpeg () then upload it to the server. Now, create a folder structure to write the following PHP script. 1. Create an HTML Form to Upload Image

How to compress image size without losing quality?

compress_image – It will compress image size without losing quality and save it to the server. This function will be within upload_image () function. File Name – compress-script.php

How to change the image quality of a file in PHP?

This function will be within upload_image () function. File Name – compress-script.php $error="Please Select files.."; In this code, by default image quality is set $imageQuality= 60 you can change its value from 60 to any other value according to your requirement.

How to compress images in PHP?

smart — automatic content-aware mode to compress images. Standard PHP functions have all the basic tools to do simple compression. Third-party open source libraries are quite advanced, with more controls such as on-the-fly compression, filters, watermarks, etc.


Video Answer


2 Answers

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.

like image 76
sectus Avatar answered Oct 20 '22 18:10

sectus


Use imagecopyresampled instead of imagecopyresized (it's the same arguments so just change the function) :)

like image 36
Lionel Paulus Avatar answered Oct 20 '22 20:10

Lionel Paulus