Scaling and Rotating
PHP offers you two different ways to resize an image, and you should choose the right one for your needs. The first option, imagecopyresized()
, allows you to change the size of an image quickly but has the downside of producing fairly low-quality pictures. When an image with detail is resized, aliasing ("jaggies") is usually visible, which makes the resized version hard to read, particularly if the resizing was to an unusual size. The other option is imagecopyresampled()
, which takes the same parameters as imagecopyresized()
and works in the same way, with the exception that the resized image is smoothed so that it is still visible. The downside here is that the smoothing takes more CPU effort, so the image takes longer to produce.
Here is an example of imagecopyresized()
in action— save it as specialeffects.php:
header("content-type: image/png"); $src_img = imagecreatefrompng("complicated.png"); $srcsize = getimagesize("complicated.png"); $dest_x = $srcsize[0] / 1.5; $dest_y = $srcsize[1] / 1.5; $dst_img = imagecreatetruecolor($dest_x, $dest_y); imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $dest_x, $dest_y, $srcsize[0], $srcsize[1]); imagepng($dst_img); imagedestroy($src_img); imagedestroy($dst_img);
There are two images being used in there. The first one, $src_img
, is created from a PNG screenshot of the online PHP manual—this contains lots of text, which highlights the aliasing problem with imagecopyresized()
nicely. The variables $dest_x
and $dest_y
are ...
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.