PHP-Imagemagick image display - php

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..

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).

you can try to display the image by this way:
// start buffering
ob_start();
$thumbnail = $im->getImageBlob();
$contents = ob_get_contents();
ob_end_clean();
echo "<img src='data:image/jpg;base64,".base64_encode($contents)."' />";

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;
}
?>

You can embed the raw image in you page, see the blog entry below for an example in page syntax.
http://www.sveinbjorn.org/news/2005-11-28-02-39-23
But i think it would be more productive to save the thumbnail on the filesystem and serve it as normal file. Otherwise you will be generating the thumbnail each time the page is accessed. Someone possibly uploaded this PDF file, so you may as well generate the thumbnail on upload time.

As I can see there are too many answers which are not accurate enough, so here goes mine:
This will print the image as you are doing it now(by the time of asking this question). As alternative to answer by #Vasil Dakov you should modify the snippet i gave you like this:
<?php
// ... Image generation goes here
header("Content-Type: image/jpeg");
ob_start();
print $im->getImageBlob();
$the_outputted_image = ob_get_flush();
?>
// Assuming that you use MVC approach and you are storing $the_outputted_image in a object and passing it to the view(ie. index.html or the HTML below the code).
//... Html code of index.html
<img src="data:image/jpg;base64 <?php print $the_outputted_image; ?>" alt="image" title="IMagick Generated Image" />
As another alternative is creating a script to generate the image, save it in some folder ( assuming img/ is the folder) and return only the path+filename+ extension to the file:
<?php
// ... Image generation goes here
header("Content-Type: image/jpeg");
$filename = 'img/' . md5(microtime()) . '.jpg'// Microtime is just as an example, you should use your own method.
$fp = fopen($filename, "x"); //Creating and opening the file for write-only
$im->writeImageFile($fp); //Writing the image to the file pointer (I would recommend writing it using, fwrite(), because it is binary-safe writing method)
fclose($fp);
?>
// Html
<img src="<?php print $filename; ?>" alt="image" title="IMagick Generated Image" />
documentation for Imagick::writeImageFile

In my case I found out a solution like this:
$im = new Imagick("http://www.yourserver.com/upload/file_name.pdf");
$im->setResolution(300, 300); // if higher image will be good to read
$im->setIteratorIndex(0); // read first page
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
ob_start();
print $im->getImageBlob();
$contents = ob_get_contents();
ob_end_clean();
echo "<img src='data:image/jpg;base64,".base64_encode($contents)."' />"; //output as image
good luck.

The only solution would be to convert your image to base64 and include it as an embedded base64 image (data:image/png;base64, ). Further reference.
But this isn't supported in IE 6 and 7.

Related

How to return image from php file set as img src

I am setting up a random image function but trying to prove the concept before handling the randomizer.
Right now I have a test.php file. It contains:
<?php
$img = 'http://example.com/img.jpg';
$fp = fopen($img, 'rb');
header('Content-type: image/jpeg;');
header("Content-Length: " . filesize($img));
fpassthru($fp);
exit;
?>
And then in another html file I have <img src="test.php">
The goal is just to return the image. The image url works is right, and test.php returns a 200. But the image just shows the little broken image icon.
I have also tried readfile() with no luck.
I am just trying to show this image.
filesize does not work on HTTP URLs. The docs say:
This function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
However, the HTTP wrapper does not support the stat function. Because of this, you send a wrong Content-Length header and the HTTP response cannot be interpreted by your browser.
I see two possible solutions:
Load the image into memory and use strlen:
$image = file_get_contents('http://example.com/img.jpg');
header('Content-type: image/jpeg;');
header("Content-Length: " . strlen($image));
echo $image;
Use the $http_response_header variable to read the remote response's Content-Length header:
$img = 'http://example.com/img.jpg';
$fp = fopen($img, 'rb');
header('Content-type: image/jpeg;');
foreach ($http_response_header as $h) {
if (strpos($h, 'Content-Length:') === 0) {
header($h);
break;
}
}
fpassthru($fp);
Another alternative would be to use some of the various built in functions for generating / manipulating images - in the case of the code below it is for a png but similar functions exist for jpg,gif and bmp.
Using a url as the filepath relies upon that setting being enabled by your host ( on dev obviously you control whether it is enabled or not )
Using these functions also gives you the possibility to add your own text at runtime, combine images and all sorts of other cool things.
<?php
if( ini_get( 'allow_url_fopen' ) ){
$imgPath='http://localhost/images/filename.png';
} else {
$imgPath=realpath( $_SERVER['DOCUMENT_ROOT'].'/images/filename.png' );
}
header("Content-type: image/png");
$image = imagecreatefrompng($imgPath);
imagesavealpha($image,true);
imagealphablending($image,true);
imagepng($image);
imagedestroy($image);
?>

In PHP, how do I use the GD library created image directly on my website

I'm not sure I understand quite how this works. For a website form I'd like to generate a random captcha image and display it along with the form. So ideally I would like something along those lines:
<form action="post.php" method="post">
...
<?php create_captcha(); ?>
</form>
While I do have a function which creates an image resource in PHP (link)
function create_captcha() {
$w = 60; $h = 30;
$img = imagecreatetruecolor($w, $h);
...
//header("Content-Type: image/jpeg");
imagejpeg($img);
}
I can't quite figure out how to output that image directly onto the website as part of the HTML form. My suspicion is that I'll have to save it into a temporary file captcha.jpg and then generate a <img src="captcha.jpg" /> into the website.
Is there a more elegant way without using a temporary image?
use your captcha generation file path as source of IMG tag
<img src="http://domain.com/your-captcha_generating-file-path" />
You could do something like this:
function getCaptcha() {
// Begin output buffering
ob_start();
// generate the captcha image in some magic way
$w = 60; $h = 30;
$img = imagecreatetruecolor($w, $h);
imagejpeg($img);
// and finally retrieve the byte stream
$rawImageBytes = ob_get_clean();
return "<img src='data:image/jpeg;base64," . base64_encode( $rawImageBytes ) . "' />";
}
By using a Base64 encoded data source in your img tag, you won't have to store any temporary files at all.

how to save random generator code image to folder

I generated the barcode by using php in kohana 2.3.
I can able to view only the barcode image.
I can't able to store that image into one folder.
I used that below code
$coupon_code = text::random($type = 'alnum', $length = 6); $img = $this->code128BarCode($coupon_code);
ob_start();
imagepng($img);
//Get the image from the output buffer
$output_img = ob_get_clean();
echo '<img type="file" name="barcode" style="height:30px;width:100px;" src="data:image/png;base64,' . base64_encode($output_img) . '" />'; exit;
help me to store that image into folder.
You must use imagepng in correct manner to save image some where. Like
imagepng($img, $saved_file_path);
See imagepng tutorial for more.

Other non-image related code before and after header no longer work

I am trying to use header('Content-type: image/jpeg') to edit and display jpeg photos as follows.
header('Content-type: image/jpeg')
$filename = 'aaa.jpg';
$im = imagecreatefromjpeg($filename);
imagefilter($im, IMG_FILTER_CONTRAST,50);
imagejpeg($im);
imagedestroy($im);
In the same file,I also have other simple codes like $abc = $_POST['abc'].
After I put the header, code before the header and code after image destroy($im) no longer work. And when I put any code such as $_post['abc'] before the header, both header and code doesn't work. All codes were fine before I included header and code to manipulate and output image. It is my first time using header('Content-type: image/jpeg') and I cannot find the answer after trying for so long. Please help. Thank you.
If you want to output html page, do not send image header. But instead, at first output the transformed image to a file on your server and add the <img> or <a>nchor tag in your html page:
<html><body>
<?php
$output_dir = 'images';
if (!file_exists($output_dir)) {
mkdir($output_dir, 0777);
}
$filename = 'aaa.jpg';
$filename2 = 'aaa2.jpg';
if (!file_exists($filename)) {
echo 'Input image not exists!'; exit;
}
$im = imagecreatefromjpeg($filename);
imagefilter($im, IMG_FILTER_CONTRAST, 50);
imagejpeg($im, $output_dir.'/'.$filename2);
imagedestroy($im);
echo 'Original image:<br/><img src="'.$filename.'" /><br/>';
echo 'Transformed image:<br/><img src="'.$output_dir.'/'.$filename2.'" />';
?>
</body></html>
That image header send in case, you want to output it as standalone image. For more examples have a look at php.net.

Displaying an image created with imagecreatefromstring

Let's say I have the code that looks something like:
<?PHP
//
//... stuff here
//
$im = imagecreatefromstring( $imageData );
echo "<img src=" . /* what goes here? */ . "alt=\"the image\" />";
//
// more stuff here
//
?>
What do I replace /* what goes here? */ with so my image data will display?
Thank you.
What do I replace /* what goes here? */ with so my image data will display?
The location you highlighted is the so called src attribute of the img HTML-tagDocs. The value is a so called URIDocs.
In your case you want that URI to point to the image data in question. You have not specified which type the image should be output as, so I will assume it's a PNG image in the following example.
You now need to convert your image data into an URI. The most straight forward URI to create from the image data is a so called data: URIWikipedia:
<?PHP
//
//... stuff here
//
$im = imagecreatefromstring( $imageData );
ob_start();
imagepng($img);
$png = ob_get_clean();
$uri = "data:image/png;base64," . base64_encode($png);
echo "<img src=" . $uri /* URI goes here */ . " alt=\"the image\" />";
//
// more stuff here
//
?>
Even this is the most straight forward way, it is not always recommended to do so because the image data will be returned with the HTML to the browser. If the image is large, this is commonly considered an overhead.
Instead of using the data: URI you can place any other URI in there as well, for example a HTTP URI that is pointing to a PHP script on your server that is returning the image. Such a script can be very simple:
<?php
$img = imagecreatefromstring($string);
header('Content-type: image/png');
imagepng($img);
This is comparable to what Marc B suggested, see his answer as well.
<?php
$img = imagecreatefromstring($string);
header('Content-type: image/jpeg');
imagejpeg($img);
should be all you need. Doing it with the image tag as you are, you'd need to output the image to a temporary file and point the image tag at that (which incurs a second HTTP request), or use a data url.
I think you can do something like this...
$src = "data:image/gif;base64," . $imageData ;
echo "<img src=\"$src\" alt=\"the image\" />";
You have to save the resource to a file first or output it using something like imagepng() in a separate request.
See imagecreatefromstring() documentation for more information.
If you want to use a Data URI scheme, you can try this instead:
<?php
// If your image is binary data. use `base64_encode($imageData)`.
$imageData = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
echo '<img src="data:image/png;base64,'. $imageData .'" />';

Categories