Wed. Oct 16th, 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

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

Leave a Reply

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