Search code examples
phpimagemagickimagick

Converting TIFF to JPG via Imagick - Terrible Result


Source image:

SOURCE

My Code:

$mgck_wnd = new Imagick();
$mgck_wnd->readImageBlob($file);
// 1 cmyk2rgb
$img_colspc = $mgck_wnd->getImageColorspace();
if ($img_colspc != imagick::COLORSPACE_RGB && $img_colspc != imagick::COLORSPACE_GRAY) {
    $profiles = $mgck_wnd->getImageProfiles('*', false); // get profiles
    $has_icc_profile = (array_search('icc', $profiles) !== false); // we're interested if ICC
    if ($has_icc_profile === false) {
        // image does not have CMYK ICC profile, we add one
        $icc_cmyk = file_get_contents('icc/Generic CMYK Profile.icc');
        $mgck_wnd->profileImage('icc', $icc_cmyk);
    }
    // Then we need to add RGB profile
    $icc_rgb = file_get_contents('icc/Generic RGB Profile.icc');
    $mgck_wnd->profileImage('icc', $icc_rgb);
    $mgck_wnd->setImageColorspace(imagick::COLORSPACE_RGB);
}
// 2 to300dpi
$img_units = $mgck_wnd->getImageUnits();
switch ($img_units) {
    case imagick::RESOLUTION_UNDEFINED: $units= 'undefined'; break;
    case imagick::RESOLUTION_PIXELSPERINCH: $units= 'PPI'; break;
    case imagick::RESOLUTION_PIXELSPERCENTIMETER: $units= 'PPcm'; break;
}
list($x_res, $y_res) = $mgck_wnd->getImageResolution();
if ($x_res == 300 && $y_res == 300 && $img_units == imagick::RESOLUTION_PIXELSPERINCH) { return null; }
$mgck_wnd->setResolution(300, 300);
$mgck_wnd->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);

// 3 tiff2jpg
$img_colspc = $mgck_wnd->getImageColorspace();
if ($img_colspc == imagick::COLORSPACE_RGB) {
    $mgck_wnd->setImageColorspace(imagick::COLORSPACE_RGB);
}
$mgck_wnd->setCompression(Imagick::COMPRESSION_JPEG);
$mgck_wnd->setCompressionQuality(85);
$mgck_wnd->setImageFormat('jpeg');
return $mgck_wnd;

Result image:

RESULT

How to fix it?

Tiff Image Example from https://file-examples.com/wp-content/uploads/2017/10/file_example_TIFF_1MB.tiff Color Profiles from https://github.com/gopalkoduri/DLIdownloader/tree/master/libs/tiff2pdf


Solution

  • The Problem was in corrupted ImageMagick 6.9 library.

    1. I compile lib from source via instruction https://imagemagick.org/script/install-source.php
    2. And then compile Imagick module for PHP from source too https://pecl.php.net/package/imagick/3.7.0 ("./configure --with-imagick=/usr/local") And all works!