Search code examples
phpimagickcmyk

PDF to PNG conversion with Imagick


I have a webpage where I have many pdf documents that are 1 page images in CMYK. I need to convert them to png/jpg to display it on the webpage. I am trying to use PHP native Imagick but stumbled upon weird issue. Code that does the conversion looks like this:

$im = new Imagick();
$im->setResolution(200, 200);
$im->readimage($file->getAbsolutePath());
$im->setImageFormat('png');
$im->transformImageColorspace(Imagick::COLORSPACE_SRGB);
$im->writeImage($file->getAbsolutePath() . '.png');

Now on my local installation everything works fine, PNG file looks like PDF document. But on my server I noticed that sometimes colors are completely inaccurate.

Here is an example:

Source pdf

Local convert result

Server convert result

The only difference I noticed is in Imagick versions reported by phpinfo:

Locally: PHP 5.5.9 Imagick: 6.7.7-10 2014-03-06 Q16

Server: PHP 5.4.42 Imagick: 6.8.9-7 Q16 x86_64 2015-03-21

Do anyone have any idea how to make server use correct color space to convert pdf into png?

[EDIT / UPDATE]

As suggested by @fab-sa I tried to use icc profiles now the code looks like:

$icc_cmyk = file_get_contents(dirname(__FILE__).'/USWebUncoated.icc');
$icc_rgb = file_get_contents(dirname(__FILE__).'/sRGB_v4_ICC_preference.icc');
$im->setResolution(200,200);
$im->readimage($file->getAbsolutePath());
$im->setImageFormat('png');
$im->profileImage('icc', $icc_cmyk);
$im->profileImage('icc', $icc_rgb);
$im->transformImageColorspace(Imagick::COLORSPACE_SRGB);
$im->writeImage($file->getAbsolutePath().'.png');

And icc profiles:

https://github.com/vivid-planet/library/blob/master/icc/sRGB_v4_ICC_preference.icc

https://github.com/nicolasfranck/Grim/blob/master/profiles/Adobe%20ICC%20Profiles/CMYK%20Profiles/USWebUncoated.icc

However still no expected result.


Solution

  • It looks like the version of Ghostscript being used on your server is not processing the pdf correctly. I get the same incorrect result with gs version 8.7 and get the correct result with 9.16

    ghostscript version 8.7

    gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=1 -sDEVICE=pngalpha -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r50 -sOutputFile=docgs8-%d.png doc.pdf

    enter image description here

    ghostscript version 9.16 downloaded from http://ghostscript.com/download/gsdnld.html

    ./gs-916-linux_x86_64 -q

    -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=1 -sDEVICE=pngalpha -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r50 -sOutputFile=docgs9-%d.png doc.pdf

    enter image description here