Search code examples
phpimagemagickimagick

PHP Imagick - display first slice of mutli image TIFF


I'm trying to display the first slice of a multi image TIFF within my HTML page. Therefore, I'm trying to use Imagemagick to somehow convert the TIFF to a widely supported format like JPG or PNG. I'm using the following code:

<?php 
$im = new imagick('my_image.tif');
$im->setImageFormat('jpeg');

header("Content-Type: image/jpeg");
ob_start();
$thumbnail = $im->getImageBlob();
$contents =  ob_get_contents();
ob_end_clean();

echo "<img src='data:image/jpg;base64,".base64_encode($thumbnail)."' />";

 ?>

This code works fine when reading a JPG file - but for TIFF files, this displays something - but not the content of my TIFF file. I guess I have to submit the TIFF-files properties, just like when I'm creating them? The TIFF-file is created in a C programm like that:

 TIFF* tif;
 tif = TIFFOpen(filename, "w");
 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, columns);
 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, rows);
 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32);
 TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);

 for (i = 0; i < rows; i++)
     TIFFWriteScanline(tif, &data[i * columns], i, 0);

 TIFFWriteDirectory(tif);
 TIFFClose(tif);

How can I convert this properly to be shown on my webpage? Additionally, how can I chose which of the images to be shown? Ideally, the user of the webpage would be able to scroll through the slices of the TIFF file. Thanks!


Solution

  • If your creating the TIFF images from C, be sure the following tags are defined, or at least set to a default value.

    • TIFFTAG_IMAGEWIDTH
    • TIFFTAG_IMAGELENGTH
    • TIFFTAG_COMPRESSION
    • TIFFTAG_FILLORDER
    • TIFFTAG_PLANARCONFIG
    • TIFFTAG_SAMPLESPERPIXEL
    • TIFFTAG_BITSPERSAMPLE
    • TIFFTAG_SAMPLEFORMAT
    • TIFFTAG_MINSAMPLEVALUE
    • TIFFTAG_MAXSAMPLEVALUE
    • TIFFTAG_PHOTOMETRIC

    See the header check in the coders/tiff.c to ensure tiff-file generation would be valid for ImageMagick use.

    I can only suggest creating a quick header validation / dump program in C to discover which header is not defaulting correctly, and adjust the TIFF generation program.