I've created a method called convertImage()
that uses Imagick
to convert any file into a jpeg
file.
I've added ICC
profiles to deal with CMYK
to RGB
conversions.
This is working well for thousands of files except for a few PSD
files.
public static function convertImage($localPath, $destination, $max_width, $max_height)
{
$image = new Imagick();
$image->readImage($localPath);
if(pathinfo($localPath, PATHINFO_EXTENSION) === "psd"){
$image->setIteratorIndex(0);
}
if ($image->getImageColorspace() == Imagick::COLORSPACE_CMYK) {
$profiles = $image->getImageProfiles('*', false);
// we're only interested if ICC profile(s) exist
$has_icc_profile = (array_search('icc', $profiles) !== false);
// if it doesnt have a CMYK ICC profile, we add one
if ($has_icc_profile === false) {
$icc_cmyk = file_get_contents(__DIR__ . '/../icc/USWebUncoated.icc');
$image->profileImage('icc', $icc_cmyk);
unset($icc_cmyk);
}
// then we add an RGB profile
$icc_rgb = file_get_contents(__DIR__ . '/../icc/sRGB_v4_ICC_preference.icc');
$image->profileImage('icc', $icc_rgb);
unset($icc_rgb);
}
$image->stripImage();
$image->setImageFormat('jpg');
$image->setImageCompressionQuality(85);
$image->writeImage($destination);
$image->clear();
$image->destroy();
// we resize files in a second time because of a imagick bug (pictures become black)
$image = new Imagick();
$image->readImage($destination);
$image->scaleImage($max_width, $max_height, true);
$image->writeImage($destination);
$image->clear();
$image->destroy();
}
For some PSD
files I got this Exception:
maximum channels exceeded `ART00060111_B.psd' @ error/psd.c/ReadPSDImage/1085
And for others:
Unable to read the file: ART00060111_A.psd
You can find the files here: [ART00060111_A.psd, ART00060111_B.psd, USWebUncoated.icc, sRGB_v4_ICC_preference.icc]
Here is my phpinfo()
concerning Imagick: