Monday 24 September 2018

PHP: How to compress images in php using gd

PHP applications might need to do some image processing if they are allowing users to upload pictures of somekind. This can include cropping, watermarking, compressing etc. To compress an image the quality needs to be adjusted. Here are few examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function compress_image($src, $dest , $quality)
{
    $info = getimagesize($src);
  
    if ($info['mime'] == 'image/jpeg')
    {
        $image = imagecreatefromjpeg($src);
    }
    elseif ($info['mime'] == 'image/gif')
    {
        $image = imagecreatefromgif($src);
    }
    elseif ($info['mime'] == 'image/png')
    {
        $image = imagecreatefrompng($src);
    }
    else
    {
        die('Unknown image file format');
    }
  
    //compress and save file to jpg
    imagejpeg($image, $dest, $quality);
  
    //return destination file
    return $dest;
}
  
//usage
$compressed = compress_image('boy.jpg', 'destination.jpg', 50);
The above function will process a jpg/gif/png image and compress it and save to jpg format. The actual compression takes place in just oneline, that is the imagejpeg function. The quality value controls the amount of compression that is applied. Lower the quality higher the compression. It should be kept in mind that compression is not lossless and will result in degradation of the image quality.
The above example creates a jpg image from the source. Alternatively the resulting image can be stored as png if transparency needs to be preserved. The function looks like this
1
imagepng($image, 'destination.png', 5);
The third parameter is the compression value whose value can be between 0-9. Higher value means higher compression and lower size. However png files are much larger in size compared to jpg images.

0 comments:

Post a Comment