All formats

GD

LanguagePHP (C extension)
LicensePHP License (extension), GD license (libgd, permissive)
Repositorygithub.com/php/php-src (ext/gd), libgd
Documentationphp.net/manual/en/book.image.php
Depends onlibpng, zlib (bundled libgd in PHP)
Read / writeyes / yes, 8-bit truecolor with alpha and palette; 16-bit is reduced to 8 bits; no text chunks

GD is PHP’s built-in image extension. It’s compiled into most PHP builds and enabled on almost every hosting provider, so code that uses it runs without installing anything. It reads and writes PNG, JPEG, GIF, WebP, AVIF and BMP, and has functions to resize, crop, rotate, draw shapes and render TrueType text.

For PNG, two things matter: call imagesavealpha($image, true) or transparency is lost on save, and use truecolor images (imagecreatetruecolor) for smooth resizing. GD doesn’t read or write PNG text chunks or color profiles, and its resize quality is lower than Imagick’s.

Installation#

Shell
# Debian / Ubuntu
sudo apt install php-gd
# check it's enabled
php -m | grep gd

On Windows, enable extension=gd in php.ini. With Docker official images: docker-php-ext-install gd.

Basic usage: read, resize and save a PNG#

PHP
<?php
$src = imagecreatefrompng('in.png');
if ($src === false) {
    exit("cannot read in.png\n");
}
$w = imagesx($src);
$h = imagesy($src);
echo "$w x $h\n";

$newW = 400;
$newH = intdiv($h * $newW, $w);
$dst = imagecreatetruecolor($newW, $newH);

// keep transparency
imagealphablending($dst, false);
imagesavealpha($dst, true);
imagefill($dst, 0, 0, imagecolorallocatealpha($dst, 0, 0, 0, 127));

imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $w, $h);
imagepng($dst, 'out.png');

imagescale($src, 400) is a shorter alternative for resizing.

How to get PNG width and height without decoding#

getimagesize reads only the header and works for any image format:

PHP
<?php
$info = getimagesize('in.png');
if ($info === false) {
    exit("not an image\n");
}
[$width, $height] = $info;
echo "$width x $height, {$info['mime']}, {$info['bits']} bits\n";

How to set PNG compression level#

The third argument of imagepng is the zlib level, 0 (none) to 9 (smallest):

PHP
<?php
imagesavealpha($image, true);
imagepng($image, 'out.png', 9);

How to output a PNG to the browser#

PHP
<?php
$image = imagecreatetruecolor(200, 100);
$bg = imagecolorallocate($image, 30, 90, 160);
$fg = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg);
imagestring($image, 5, 50, 40, 'Hello PNG', $fg);

header('Content-Type: image/png');
imagepng($image);  // no file name: writes to the output

How to convert PNG to JPEG#

Copy the PNG onto a white canvas so transparent areas don’t turn black:

PHP
<?php
$png = imagecreatefrompng('in.png');
$w = imagesx($png);
$h = imagesy($png);
$jpg = imagecreatetruecolor($w, $h);
imagefill($jpg, 0, 0, imagecolorallocate($jpg, 255, 255, 255));
imagecopy($jpg, $png, 0, 0, 0, 0, $w, $h);
imagejpeg($jpg, 'out.jpg', 85);

Tips#