Juno_okyo

Compress images in PHP using GD

Jan 27th, 2015
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.74 KB | None | 0 0
  1. <?php
  2. // Source: http://www.binarytides.com/compress-images-php-using-gd/
  3.  
  4. function compress_image($src, $dest , $quality)
  5. {
  6.     $info = getimagesize($src);
  7.  
  8.     if ($info['mime'] == 'image/jpeg')
  9.     {
  10.         $image = imagecreatefromjpeg($src);
  11.     }
  12.     elseif ($info['mime'] == 'image/gif')
  13.     {
  14.         $image = imagecreatefromgif($src);
  15.     }
  16.     elseif ($info['mime'] == 'image/png')
  17.     {
  18.         $image = imagecreatefrompng($src);
  19.     }
  20.     else
  21.     {
  22.         die('Unknown image file format');
  23.     }
  24.  
  25.     //compress and save file to jpg
  26.     imagejpeg($image, $dest, $quality);
  27.  
  28.     //return destination file
  29.     return $dest;
  30. }
  31.  
  32. //usage
  33. $compressed = compress_image('boy.jpg', 'destination.jpg', 50);
Add Comment
Please, Sign In to add comment