Echo missing after generating image - php

$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header('Content-Type: image/png');
imagepng($im);
//echo '<a href=\'imagepng('.$im.')\'> Download </a>';
echo "-----------------";
} else {
echo 'An error occurred.';
}
It shows the image but does not echo "==============".

You told the browser to expect an image, therefore it's only expecting an image. Everything sent will be considered part of the data for that image. And no, it won't convert text you send into part of the image.

This is because of your
header('Content-Type: image/png');
It prevents you from echoing something else than the picture on this page.
(Well it doens't, but your Browser thinks this still part of the picture)
If you want to echo picture and Text, you need a seperat file, e.g. like this
echo '<img source="./pic.php" alt="pic" height="20" width="20" />';
echo '______________';
wehere pic.php is the path to the file wich echos the picture.

There's a way of displaying both. As a disclaimer, I shall add not to use this in production, though. Not all browsers support this and it ain't purty:
header('Content-Type: text/html');
ob_start();
imagepng($im);
$data = base64_encode(ob_get_clean());
printf('<img src="data:image/png;base64,%s" />', $data);
print('---------');

You are generating an image (hence the header) so if you echo something after that, you are basically echoing "---" after the bytes of the image.
Your browser thinks your .php script is an image now and doesn't display the '---' as plain text and tries to add it to the image.

Related

Transferring and displaying image from remote location

I need to read an image (based on HTTP) on an SSL connection. This script reads the image location and encodes/decodes it, then transfers the file contents and returns the image. However, I keep getting the error cannot be displayed because it contains errors.
Here is my code:
<?php
$image = 'http://www.teleovronnaz.ch/webcam/ovronnazweb.jpg';
$info = getimagesize($image);
$strFileExt = image_type_to_extension($info[2]);
if($strFileExt == '.jpg' or $strFileExt == '.jpeg'){
header('Content-Type: image/jpeg');
}elseif($strFileExt == '.png'){
header('Content-Type: image/png');
}elseif($strFileExt == '.gif'){
header('Content-Type: image/gif');
}else{
die('not supported');
}
if($strFile != ''){
$cache_ends = 60*60*24*365;
header("Pragma: public");
header("Cache-Control: maxage=". $cache_ends);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_ends).' GMT');
$img_safe = file_get_contents($strFile);
echo $img_safe;
}
exit;
?>
This worked for me.
<?php
$url = 'http://www.teleovronnaz.ch/webcam/ovronnazweb.jpg';
header('Content-type: image/jpeg');
readfile($url);
?>
I don't know why you do it so complicated. I just stripped your cache handling, but really
<?PHP
$image = 'http://www.teleovronnaz.ch/webcam/ovronnazweb.jpg';
$imageContent = file_get_contents($image);
header("Content-Type: image/jpeg");
echo $imageContent;
die(1);
?>
Is enough to display the image. No base64 or additional stuff needed. And if the url is static, you don't even need the distinction of the file extension. You stated an image - that's singular. So I'm guessing that's the only use case here.
I just took some more time to explain a few things:
read an image (based on HTTP) on an SSL connection
If it's HTTP, there is no SSL. That's what HTTPS is for.
This script reads the image location and encodes/decodes it,
I don't know what you think, but it is not. It is base64_encoding the URL to directly decode it again into another variable. That's like doing the following: 0 is your $image - then you make $image+1 (base64_encode) - which will result in 1 - then you do $image-1 (base64_decode) which will result in 0 again.

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.

saving an image from the browser issue

I'm using code to print an image without showing the real path for it. But I have a problem when I want to save that image to my computer because its always show the PHP file name as the name for the image.
$id = intval($_REQUEST["id"]);
$getimage = $db->query("select id,img from bbup where id='$id'");
$fetch_image = $db->fetch($getimage);
$filename = $fetch_image['img'];
if (!$id) {
echo "Wrong Id";
exit;
}
if (!file_exists($filename)) {
echo "Image not found.";
exit;
}
$aaa = SITE_URL . $filename;
$imginfo = getimagesize($aaa);
header("Content-type: " . $imginfo['mime']);
readfile($aaa);
The php file is ppupload.php and when I want to save the image (let's say it is a PNG image) in the dialog box the name of the file show ( ppupload.php.png ) and I want it to be the image itself.
The image path stored into the database like this: folder/folder/filename.ext.
Have you tried setting the Content Disposition header?
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Type: application/octet-stream');
This might help.
You can try to add something like this header("Content-Disposition: inline; filename=\"myimg.png\"");

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

Image to browser without saving

How can I put image from the memory to the browser, without saving.
For example:
function getImage()
{
$imageFile = imagecreatefromjpeg('Map.jpg');
$imageObject = imagecreatefrompng('image2.png');
imagealphablending($imageFile, true);
imagecopy(....);
$ret = array($imageFile, $imageObject) ;
return $ret
}
<?php $ret = getImage(); ?>
<img src = <?php $ret[0];? alt=''>
Is this possible, without saving?
Yes,
Just try imagejpeg($img);
and put into <img src= path to the PHP script which render the image
See sample at: http://php.net/manual/en/function.imagecreatefromjpeg.php
Maybe if you would code your image to base64 and use it like that, it would work:
<?php
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
?>
HTML:
<img src="data:image/jpg;base64,R0lGODlhCgAKAJEAAAAAAP///81Wv81WvyH5BAEAAAMALAAAAAAKAAoAAAIUjIViq+x7QpunwXoZ lXFu/mjIUgAAOw==" alt="image" />
I infered that you want to do this in one request.
You should have a script which sends proper headers and then it should be recognized as an image by the browser. Something like:
<?php
ob_start();
// assuming you have image data in $imagedata
$length = strlen($imagedata);
header('Last-Modified: '.date('r'));
header('Accept-Ranges: bytes');
header('Content-Length: '.$length);
header('Content-Type: image/jpeg');
print($imagedata);
ob_end_flush();
?>

Categories