
PHP and ImageMagick: Wrong Resolution After Converting TIF to JPEG
I spent like two hours trying to figure this mofo out.
Imagick incorrect image dimensions after conversion to JPEG
I downloaded a TIFF image file that PHP always converted using Imagick to a small thumbnail resolution (width and height dimensions). I couldn’t find out the culprit. The TIF image had resolution of e.g. 3562×5215 pixels, but the converted JPEG would come to something like 109×160 pixels.
I tried to resize image, set size, set geometry using Imagick, but nothing worked. Even if I resized the image in PHP, it would just do a bi-cubic interpolation and clearly come out blurry as when you try to upscale a thumbnail to a larger size.
convert would also show warning as shown in the featured image.
identify command would show:
Image:
[...]
Geometry: 3562x5215+0+0
Page geometry: 3562x5215+0+0
Image: // another one shown, the incorrect (likely thumbnail (?) dimensions)
Geometry: 109x160+0+0
Page geometry: 109x160+0+0
Exif tool would show correct dimensions, but that’s just meta data.
Solution? Use Imagick::coalesceImages() function!
$imagick = $imagick->coalesceImages();
This returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence. It works for one image as well as was my case, e.g. not multiple images in a sequence as PHP documentation says.
Finally the JPEG file output of Imagick is in correct resolution as the original TIF image!
Example PHP code with comments – coalesceImages and correct dimensions after conversion
const TEMP_IMAGE = 'path/to/image.tiff';
print_r(getimagesize(TEMP_IMAGE));
$imagick = new Imagick();
$imagick->readImage(TEMP_IMAGE);
$exif_data = exif_read_data(TEMP_IMAGE);
$imagick = $imagick->coalesceImages();
/* THIS DOES NOT WORK:
$imagick->setImageResolution($real_width, $real_height);
$imagick->setImageProperty('Geometry', $real_width . 'x' . $real_height . '+0+0');
$imagick->setPage($real_width, $real_height, 0, 0);
$imagick->setImagePage($real_width, $real_height, 0, 0);
$imagick->setSize($real_width, $real_height);
$imagick->setImageExtent($real_width, $real_height); // this just puts thumbnail on black background of the correct size
$imagick->resizeImage($real_width, $real_height, Imagick::FILTER_CUBIC, 1); // blurry upscaled thumbnail comes out
print_r($imagick->getImageGeometry()); // still the same (small size) geometry shown!
*/
$imagick->setImageFormat('jpeg');
$imagick->setCompressionQuality(90);
$imagick->writeImage(FILE_IMAGE); // finally correct dimensions after Imagick::coalesceImages() call
$imagick->clear();
$imagick->destroy();