Imagick (TIFF)
| Language | PHP |
|---|---|
| License | PHP License 3.01 (ImageMagick license for ImageMagick) |
| Repository | github.com/Imagick/imagick |
| Documentation | php.net/imagick |
| Depends on | ImageMagick (with libtiff) |
| Read / write | yes / yes, multi-page, CMYK, 16-bit, BigTIFF (TIFF64), all common compressions |
Imagick is a native PHP extension that wraps the ImageMagick library. It reads and writes TIFF through libtiff, including multi-page files, CMYK and 16-bit images and fax compression. An Imagick object holds a list of images: for a TIFF each page is one image, so you can loop over pages, add pages and write them all to one file.
Installation#
Shell
# Debian / Ubuntu
sudo apt install php-imagick
# macOS (Homebrew PHP)
brew install imagemagick && pecl install imagick
Check TIFF support with php -r 'print_r(Imagick::queryFormats("TIFF*"));'.
Basic usage: convert a TIFF to PNG#
PHP
<?php
$im = new Imagick();
$im->readImage('in.tif[0]'); // [0] reads only the first page
echo $im->getImageWidth(), ' x ', $im->getImageHeight(), "\n";
$im->setImageFormat('png');
$im->writeImage('out.png');
$im->clear();
How to save a TIFF with compression#
PHP
<?php
$im = new Imagick('in.png');
$im->setImageFormat('tiff');
$im->setImageCompression(Imagick::COMPRESSION_LZW); // or COMPRESSION_ZIP, COMPRESSION_JPEG, COMPRESSION_GROUP4
$im->writeImage('out.tif');
For COMPRESSION_JPEG set the quality with $im->setImageCompressionQuality(85). COMPRESSION_GROUP4 needs a black-and-white image ($im->thresholdImage(0.5 * Imagick::getQuantum()) first).
How to split a multi-page TIFF into pages#
PHP
<?php
$doc = new Imagick('scan.tif');
echo $doc->getNumberImages(), " pages\n";
foreach ($doc as $i => $page) {
$page->setImageFormat('png');
$page->writeImage("page-$i.png");
}
How to merge images into a multi-page TIFF#
PHP
<?php
$doc = new Imagick();
foreach (['page1.png', 'page2.png', 'page3.png'] as $file) {
$page = new Imagick($file);
$page->setImageFormat('tiff');
$page->setImageCompression(Imagick::COMPRESSION_LZW);
$doc->addImage($page);
}
$doc->writeImages('pages.tif', true); // true = all images into one file
How to read TIFF properties and resolution#
ImageMagick exposes TIFF tags as tiff:* properties:
PHP
<?php
$im = new Imagick('in.tif');
print_r($im->getImageProperties('tiff:*')); // tiff:software, tiff:photometric, tiff:endian...
print_r($im->getImageResolution()); // ['x' => 300, 'y' => 300]
echo $im->getImageCompression(), "\n"; // an Imagick::COMPRESSION_* value
How to convert a multi-page TIFF to PDF#
PHP
<?php
$doc = new Imagick('scan.tif');
$doc->setImageFormat('pdf');
$doc->writeImages('scan.pdf', true);
Tips#
- Use
$im->pingImage('in.tif')to read size and properties without decoding pixels. - To write BigTIFF, set the format to
TIFF64:$im->setImageFormat('TIFF64'). - Set
$im->setOption('tiff:predictor', '2')before writing LZW or Zip TIFF for smaller photos.