Using PHP’s Imagick class to convert a CMYK jpeg to RGB
October 24th, 2008 | by: Chris Woodford
We’ve recently converted all of our image processing from using GD to using ImageMagick and one of the biggest stumbling blocks in doing that has been the lack of documentation for PHP’s Imagick class. I ran into a problem when I realized that I needed to convert a jpeg from CMYK to RGB. After some googling, I was only able to find a solution that used imagemagick on the command line. This just isn’t a viable solution for my current needs, I need a solution in PHP, preferably using the Imagick class. Back to google. I finally find what appears to be exactly what I’m looking for, but it’s on one of those question/answer sites where you have to pay to see the answer. Forget that! So I read through the little Imagick documentation that exists and trial-and-errored my way to a working solution.
Here’s a simple script that gives a run through of converting a CMYK jpeg to RGB using ImageMagick’s Imagic class:
<?php
$filePath = '/path/to/your/file.jpg';
$i = new Imagick($filePath);
$cs = $i->getImageColorspace();
if ($cs == Imagick::COLORSPACE_CMYK) {
print "Image is CMYK<br/>\n";
?>
CMYK Image:<br/>
<img src="<?=$filePath ?>"/>
<br/><br/>
<?php
$i->setImageColorspace(Imagick::COLORSPACE_SRGB);
$i->setImageFormat('jpeg');
$cs = $i->getImageColorspace();
if ($cs != Imagick::COLORSPACE_CMYK) {
print "Image is no longer CMYK<br/>\n";
// write it to a temp file
$filePath = '/path/to/temp/file.jpg';
$i->writeImage($filePath);
}
} else {
print "Image is not CMYK<br/>\n";
}
if ($cs == Imagick::COLORSPACE_SRGB ||
$cs == Imagick::COLORSPACE_RGB){
print "Image is RGB<br/>\n";
}
?>
RGB Image:<br/>
<img src="<?=$filePath ?>"/>
<?php
$i->clear();
$i->destroy();
$i = null;
Hopefully this will help some of you out! I know there are a lot of people out there looking for the same (or at least a similar) solution.
Digg it!