How to compress images in PHP?

Posted on

Coding Problem :

On my site, people can post messages and along with these messages an image (which is saved in a folder). I would like to know if there is any class or some means using PHP to compress these images without losing quality.

Note: Extensions accepted: .jpg and .png


asked by anonymous 13.03.2015 / 20:02

Answer :

Answer 1 :

You can test for quality loss by using PHP GD and see if it suits you. you can also do this while uploading the image:

function compressImage($source_path, $destination_path, $quality) {
    $info = getimagesize($source_path);

    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source_path);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source_path);

    imagejpeg($image, $destination_path, $quality);

    return $destination_path;

Explaining the functions used:

  • getimagesize() : returns the image information (type, size, dimensions, etc.), we use to achieve the MIME Type of the original image.
  • imagecreatefromjpeg() : creates a new image from the original image.
  • imagejpeg() : send an image to the browser or to a file, this is where the lighter image is created.

Finally the function returns the path of the lighter image.

Usage example: $img = compressImage("images/praia.jpg", "images/compressed/compressed_praia.jpg", 6);


Answer 2 :

There are several image processing libraries, some of which I know are:

I’d advise using Imagemagick ( that’s the reason ).

Some things you can do to make sweating images look smaller.




    $image = new Imagick();

    $image->thumbnailImage(800, 300);




Answer 3 :

Answer 4 :

Answer 5 :

Answer 6 :

Answer 7 :

Answer 8 :

Answer 9 :

Leave a Reply

Your email address will not be published.