GD
| Language | PHP 7.2 or later (C extension) |
|---|---|
| License | PHP License (extension), GD license (libgd, permissive) |
| Repository | github.com/php/php-src (ext/gd), libgd |
| Documentation | imagecreatefrombmp, imagebmp |
| Depends on | nothing extra for BMP (bundled libgd) |
| Read / write | yes, 1-32 bit, RLE4, RLE8 / yes, 24-bit (truecolor) or 8-bit (palette), optional RLE |
GD is PHP’s built-in image extension, enabled on almost every hosting provider. Since PHP 7.2 it reads BMP with imagecreatefrombmp and writes it with imagebmp, next to PNG, JPEG, GIF, WebP and AVIF.
imagebmp writes truecolor images as 24-bit BMP and palette images as 8-bit BMP. Its third argument, $compressed, defaults to true, which RLE-compresses palette images. Some programs and devices can’t read RLE files, so pass false when the output goes to unknown software. Alpha is not saved.
Installation#
Shell
# Debian / Ubuntu
sudo apt install php-gd
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 BMP#
PHP
<?php
$src = imagecreatefrombmp('in.bmp');
if ($src === false) {
exit("cannot read in.bmp\n");
}
echo imagesx($src) . ' x ' . imagesy($src) . "\n";
$small = imagescale($src, intdiv(imagesx($src), 2)); // height keeps the aspect ratio
imagebmp($small, 'out.bmp', false); // false: uncompressed
How to get BMP width and height without decoding#
PHP
<?php
$info = getimagesize('in.bmp');
if ($info === false) {
exit("not an image\n");
}
[$width, $height] = $info;
echo "$width x $height, {$info['mime']}, {$info['bits']} bits per pixel\n";
How to convert PNG to BMP#
Copy the PNG onto a white canvas so transparent areas don’t turn black, then save:
PHP
<?php
$png = imagecreatefrompng('in.png');
$w = imagesx($png);
$h = imagesy($png);
$out = imagecreatetruecolor($w, $h);
imagefill($out, 0, 0, imagecolorallocate($out, 255, 255, 255));
imagecopy($out, $png, 0, 0, 0, 0, $w, $h);
imagebmp($out, 'out.bmp', false); // 24-bit BMP
How to write an 8-bit RLE-compressed BMP#
Convert to a palette image first; RLE only applies to palette images:
PHP
<?php
$image = imagecreatefrombmp('in.bmp');
imagetruecolortopalette($image, true, 256); // dither, max 256 colors
imagebmp($image, 'rle8.bmp'); // $compressed defaults to true
How to convert BMP to PNG or JPEG#
PHP
<?php
$image = imagecreatefrombmp('in.bmp');
imagepng($image, 'out.png', 9);
imagejpeg($image, 'out.jpg', 85);
Tips#
imagecreatefromstring($bytes)also recognizes BMP data, e.g. from an upload.- Since PHP 8.0, GD images are
GdImageobjects and are freed automatically;imagedestroyisn’t needed. imagetypes() & IMG_BMPtells whether your GD build supports BMP.