Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP-Imagemagick image display

I have php code which create pdf thumbnail as follows;

<?php
$file ="test.pdf";
$im = new imagick(realpath($file).'[0]');
$im->setImageFormat("png");
$im->resizeImage(200,200,1,0);
header("Content-Type: image/jpeg");
$thumbnail = $im->getImageBlob();
echo $thumbnail;
?>

Which is working well. But if I want to display the image in a web page, I have to use <img src=""> tag. Is there any way to remove header("Content-Type: image/jpeg"); from the syntax and echo image using <img src="">..? Or anybody tell me how to use the syntax to display the image inside a web page.

I am running apache with php5 in my Windows Vista PC..

like image 762
Alfred Avatar asked May 22 '11 11:05

Alfred


2 Answers

With Imagick, you could use base64 encoding:

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

However, this method is kind a slow and therefore I recommend generating and saving the image earlier $img->writeImage($path).

like image 154
sluijs Avatar answered Nov 03 '22 03:11

sluijs


Embedding an image using base64 is a COMPLETELY wrong way to go about the problem esp. with something stateless like a php web script.

You should instead use http parameters to have a single php file which can perform two tasks - the default will send html , and the parameter will instruct the php file to print the image. Below is the "standard" way to do it -

<?php
if (!array_key_exists('display',$_GET))
{
    print('<html><head></head><body><img src="'.$_SERVER['PHP_SELF'].'?display=image"></body></html>');
} else
{
    // The display key exists which means we want to display an image
    $file ="test.pdf";
    $im = new imagick(realpath($file).'[0]');
    $im->setImageFormat("png");
    $im->resizeImage(200,200,1,0);
    header("Content-Type: image/jpeg");
    $thumbnail = $im->getImageBlob();
    echo $thumbnail;
}
?>
like image 45
Chetan Chauhan Avatar answered Nov 03 '22 04:11

Chetan Chauhan