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 |
| Depends on | ImageMagick 6 or 7 (MagickWand) |
| Read / write | yes / yes, all color types and bit depths, text chunks |
Imagick binds the ImageMagick library to PHP. It reads and writes over 100 formats and has better resize quality than GD (Lanczos and other filters), color management, and full access to PNG options: bit depth, color type, compression level and text chunks.
It needs ImageMagick on the server and the imagick extension from PECL or your distribution, so it’s less widely available than GD on shared hosting.
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 PNG#
PHP
<?php
try {
$image = new Imagick('in.png');
echo $image->getImageWidth() . ' x ' . $image->getImageHeight() . "\n";
$image->resizeImage(400, 0, Imagick::FILTER_LANCZOS, 1); // height 0 keeps the aspect ratio
$image->writeImage('out.png');
} catch (ImagickException $e) {
echo 'error: ' . $e->getMessage() . "\n";
}
How to get PNG width and height without decoding#
pingImage reads only the header:
PHP
<?php
$image = new Imagick();
$image->pingImage('in.png');
$geo = $image->getImageGeometry();
echo "{$geo['width']} x {$geo['height']}\n";
How to set PNG compression level and strip metadata#
PHP
<?php
$image = new Imagick('in.png');
$image->setOption('png:compression-level', '9'); // 0 .. 9
$image->setOption('png:exclude-chunks', 'date,time');
$image->stripImage(); // remove text, Exif and ICC chunks
$image->writeImage('small.png');
How to read and write PNG text chunks#
Text chunks (tEXt, zTXt, iTXt) are image properties:
PHP
<?php
$image = new Imagick('in.png');
foreach ($image->getImageProperties('*') as $key => $value) {
echo "$key: $value\n";
}
$image->setImageProperty('Title', 'Sunset');
$image->writeImage('out.png');
How to make a thumbnail#
thumbnailImage resizes and removes metadata, which keeps thumbnails small:
PHP
<?php
$image = new Imagick('in.png');
$image->thumbnailImage(200, 200, true); // fit inside 200x200
$image->writeImage('thumb.png');
How to convert PNG to JPEG#
PHP
<?php
$image = new Imagick('in.png');
$image->setImageBackgroundColor('white');
$image = $image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); // remove transparency
$image->setImageFormat('jpeg');
$image->setImageCompressionQuality(85);
$image->writeImage('out.jpg');
Tips#
$image->getImageBlob()returns the encoded file as a string, e.g. for an HTTP response.- Limit resources for untrusted uploads with
Imagick::setResourceLimit(Imagick::RESOURCETYPE_MEMORY, ...)or ImageMagick’spolicy.xml. $image->getImageDepth()and$image->getImageType()report bit depth and color type.