Mon. Dec 9th, 2019

Codes

Codes for Coders

PHP compress and resize image without loosing quality

1 min read
Images Compress by Rishap Gandhi

Images Compress by Rishap Gandhi

Images Compress by Rishap Gandhi

Today I am going to tell you about the Image compress and even resize the image without losing the quality of images. When you search examples for image compress and resize most to time it is hard to find. Here I will give you a simple of both in one function and you can further customize as per your requirement.

<?php
function compress_image($source_url, $destination_url, $quality) {
   $info = getimagesize($source_url);
   if ($info['mime'] == 'image/jpeg')
      $image = imagecreatefromjpeg($source_url);
   elseif ($info['mime'] == 'image/gif')
      $image = imagecreatefromgif($source_url);
   elseif ($info['mime'] == 'image/png')
      $image = imagecreatefrompng($source_url);
   imagejpeg($destination_url, $destination_url, $quality);
   list($width, $height) = getimagesize($source_url);
   $y = (200*$height/$width);
   $thumb = imagecreatetruecolor(200, $y);
   $source = imagecreatefromjpeg($source_url);
   imagecopyresized($thumb, $source, 0, 0, 0, 0, 200,$y, $width, $height);
   imagejpeg($thumb, $destination_url, $quality);
   return $destination_url;
}?>

If this function we are first compressing the image and then resizing the compressed image with width 200px and calculating the height as per image dimension.

You can download the sample from here :

Download Code by Rishap GandhiCompress and Resize of Image in PHP by Rishap Gandhi

PHP compress and resize image without loosing quality

4 thoughts on “PHP compress and resize image without loosing quality

  1. Is this code coplete?
    I downloaded index.php and try to upload and compress but with error:

    Warning: imagejpeg() expects parameter 1 to be resource, string given in /home/…/a/index.php on line 15

    Warning: file_get_contents(compressed/c.jpg): failed to open stream: No such file or directory in /home/…/a/index.php on line 39

Leave a Reply

Your email address will not be published. Required fields are marked *