All formats

Imagick

LanguagePHP
LicensePHP License 3.01 (ImageMagick license for the library; Ghostscript, needed for PS, is AGPL-3.0)
Repositorygithub.com/Imagick/imagick
Documentationphp.net/imagick
Depends onImageMagick (MagickWand), Ghostscript for reading PostScript
Read / writeyes (rasterized through Ghostscript) / yes (raster images wrapped in PostScript)

Imagick exposes ImageMagick’s MagickWand API as PHP classes. When you read a .ps file, ImageMagick runs Ghostscript and loads each page as a frame of the Imagick object. Writing PostScript wraps the pixels in a PostScript program.

Call setResolution() before readImage(): it sets the dpi at which Ghostscript renders. The output is always raster.

Installation#

Shell
# Debian / Ubuntu
sudo apt install php-imagick ghostscript
# macOS (Homebrew PHP)
brew install imagemagick ghostscript
pecl install imagick

Many Linux distributions disable PostScript in ImageMagick’s policy.xml (<policy domain="coder" rights="none" pattern="PS" />). If reading fails with “not authorized”, change that policy for the formats you need.

Basic usage: render every page of a PostScript file to PNG#

PHP
<?php
try {
    $im = new Imagick();
    $im->setResolution(150, 150);   // before readImage
    $im->readImage('in.ps');

    foreach ($im as $i => $page) {
        $page->setImageBackgroundColor('white');
        $page->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
        $page->setImageFormat('png');
        $page->writeImage(sprintf('page-%03d.png', $i + 1));
    }
    $im->clear();
} catch (ImagickException $e) {
    echo 'Error: ', $e->getMessage(), "\n";
}

How to render only the first page#

Add [0] to the file name to read one page (0-based):

PHP
$im = new Imagick();
$im->setResolution(300, 300);
$im->readImage('in.ps[0]');
$im->setImageFormat('png');
$im->writeImage('page1.png');

How to count pages in a PostScript file#

PHP
$im = new Imagick();
$im->pingImage('in.ps');          // still runs Ghostscript, but keeps no pixels
echo $im->getNumberImages(), " pages\n";

How to make a thumbnail of a PostScript file#

PHP
$im = new Imagick();
$im->setResolution(72, 72);
$im->readImage('in.ps[0]');
$im->setImageBackgroundColor('white');
$im = $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$im->thumbnailImage(300, 300, true);
$im->setImageFormat('jpeg');
$im->writeImage('thumb.jpg');

How to save an image as PostScript#

PHP
$im = new Imagick('photo.jpg');
$im->setImageFormat('ps3');       // ps, ps2 or ps3 (compressed)
$im->writeImage('photo.ps');

Tips#