Imagick
| Language | PHP (C extension) |
|---|---|
| License | PHP License 3.01 (extension), ImageMagick License (library) |
| Repository | github.com/Imagick/imagick |
| Documentation | php.net/manual/en/book.imagick.php, ImageMagick formats |
| Depends on | ImageMagick 6 or 7 (MagickWand) |
| Read / write | yes, all common variants including RLE and OS/2 / yes, BMP2, BMP3, V4/V5, 16-bit subtypes |
Imagick binds the ImageMagick library to PHP. It reads BMP files with any common bit depth, RLE compression, bit fields and OS/2 headers, and writes BMP with the header version and pixel layout you choose.
ImageMagick’s default BMP writer uses a V4 or V5 header when the image has alpha, gamma or a color profile. Images converted from PNG or JPEG usually have gamma set, so the output gets a V4 header that some old programs can’t read. Set the format to BMP3 to always get the classic 40-byte header.
Installation#
Shell
# Debian / Ubuntu
sudo apt install php-imagick
# or from PECL (needs ImageMagick development files)
pecl install imagick
Basic usage: read, resize and save a BMP#
PHP
<?php
try {
$image = new Imagick('in.bmp');
echo $image->getImageWidth() . ' x ' . $image->getImageHeight() . "\n";
$image->resizeImage(640, 0, Imagick::FILTER_LANCZOS, 1); // height 0 keeps the aspect ratio
$image->writeImage('out.bmp');
} catch (ImagickException $e) {
echo 'error: ' . $e->getMessage() . "\n";
}
How to write a BMP that old programs can read#
PHP
<?php
$image = new Imagick('in.png');
$image->setImageBackgroundColor('white');
$image = $image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); // remove alpha
$image->setImageFormat('BMP3'); // 40-byte BITMAPINFOHEADER, 24-bit
$image->writeImage('out.bmp');
The BMP3: prefix in the file name does the same: $image->writeImage('BMP3:out.bmp').
How to get BMP width and height without decoding#
PHP
<?php
$image = new Imagick();
$image->pingImage('in.bmp');
echo $image->getImageWidth() . ' x ' . $image->getImageHeight()
. ', ' . $image->getImageFormat() . "\n"; // BMP, BMP3 or BMP2
How to write a 16-bit RGB565 BMP#
Many small LCD displays use 16-bit 5-6-5 pixels:
PHP
<?php
$image = new Imagick('in.png');
$image->setOption('bmp:subtype', 'RGB565'); // also RGB555, ARGB1555, ARGB4444
$image->writeImage('out565.bmp');
How to convert BMP to PNG#
PHP
<?php
$image = new Imagick('in.bmp');
$image->setImageFormat('png');
$image->writeImage('out.png');
Tips#
$image->getImageBlob()returns the encoded BMP as a string, e.g. for an HTTP response withContent-Type: image/bmp.- Limit resources for untrusted uploads with
Imagick::setResourceLimit()or ImageMagick’spolicy.xml.