DEV Community

Cover image for 3 hacks when resizing images with GD in PHP
Onelinerhub
Onelinerhub

Posted on

3 hacks when resizing images with GD in PHP

1. Better antialiasing with GD based on resampling

GD has shitty antialiasing implementation, but this can be quickly fixed with a simple hack:

<?php

$im = imagecreatetruecolor(4000, 3000);
imageantialias($im, true);

$c_black = imageColorAllocate($im, 0,0,0);
$c_green = imageColorAllocate($im, 46,204,64);

imagefilledellipse($im, 2000, 1500, 800, 800, $c_green);

$imf = imagecreatetruecolor(400, 300);
imagecopyresampled($imf, $im, 0,0,0,0, 400,300,4000,3000);

imagePng($imf, '/tmp/image.png');
Enter fullscreen mode Exit fullscreen mode
  • 4000, 3000 - we have created initial image of large size (10x what we need in result),
  • imagecopyresampled - now we resize source large image (4000x3000) to resulting image (400x300) to apply better antialiasing.

Open original or edit on Github.

2. Resize an image proportionally

<?php

$file = '/var/www/examples/heroine.png';
$size = getimagesize($file);
$im = imagecreatefrompng($file);

$w = 400;
$h = $w * $size[1] / $size[0];

$imf = imagecreatetruecolor($w, $h);
imagecopyresampled($imf, $im, 0,0,0,0, $w,$h,$size[0],$size[1]);

imagePng($imf, '/tmp/image.png');
Enter fullscreen mode Exit fullscreen mode
  • $w = 400 - resize image to 400 pixels wide,
  • $w * $size[1] / $size[0] - calculates resized image height based on source image proportions.

Open original or edit on Github.

3. Resize transparent PNG image

<?php

$file = '/var/www/examples/clouds.png';
$size = getimagesize($file);
$im = imagecreatefrompng($file);

$w = 300;
$h = $w * $size[1] / $size[0];

$imf = imagecreatetruecolor($w, $h);
imagealphablending($imf, false);
imagesavealpha($imf, true);
imagecopyresampled($imf, $im, 0,0,0,0, $w,$h,$size[0],$size[1]);

imagePng($imf, '/tmp/image.png');
Enter fullscreen mode Exit fullscreen mode
  • imagealphablending - we're disabling alpha blending to prevent transparent background being converted to black color,
  • imagesavealpha - we're enabling alpha channel (controls transparency) for resulting image.

Open original or edit on Github.

Oldest comments (0)