Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a PHP page as an image

I am trying to read a image file (.jpeg to be exact), and 'echo' it back to the page output, but have is display an image...

my index.php has an image link like this:

<img src='test.php?image=1234.jpeg' /> 

and my php script does basically this:

1) read 1234.jpeg 2) echo file contents... 3) I have a feeling I need to return the output back with a mime-type, but this is where I get lost

Once I figure this out, I will be removing the file name input all together and replace it with an image id.

If I am unclear, or you need more information, please reply.

like image 568
MichaelICE Avatar asked May 22 '09 22:05

MichaelICE


People also ask

How to return image file in PHP?

php // open the file in a binary mode $name = './img/ok. png'; $fp = fopen($name, 'rb'); // send the right headers header("Content-Type: image/png"); header("Content-Length: " . filesize($name)); // dump the picture and stop the script fpassthru($fp); exit; ?>

Can you echo an image in PHP?

You cant echo an image using PHP. echo is for strings only. However, you can echo the image source - img src="" Just make sure you put the picture extension at the end of the file you are grabbing.

How Copy image from one page to another in PHP?

We need more details. if you already have the info you need in $_POST there is no reson to put it in a $_SESSION. $_POST is usaly obtaind from a <FORM> on the first page or by an AJAX-request. $imageName=$_GET['image'];

How can I use image in PHP?

Create The Upload File PHP Script $target_file specifies the path of the file to be uploaded. $uploadOk=1 is not used yet (will be used later) $imageFileType holds the file extension of the file (in lower case) Next, check if the image file is an actual image or a fake image.


1 Answers

The PHP Manual has this example:

<?php // open the file in a binary mode $name = './img/ok.png'; $fp = fopen($name, 'rb');  // send the right headers header("Content-Type: image/png"); header("Content-Length: " . filesize($name));  // dump the picture and stop the script fpassthru($fp); exit; ?> 

The important points is that you must send a Content-Type header. Also, you must be careful not include any extra white space (like newlines) in your file before or after the <?php ... ?> tags.

As suggested in the comments, you can avoid the danger of extra white space at the end of your script by omitting the ?> tag:

<?php $name = './img/ok.png'; $fp = fopen($name, 'rb');  header("Content-Type: image/png"); header("Content-Length: " . filesize($name));  fpassthru($fp); 

You still need to carefully avoid white space at the top of the script. One particularly tricky form of white space is a UTF-8 BOM. To avoid that, make sure to save your script as "ANSI" (Notepad) or "ASCII" or "UTF-8 without signature" (Emacs) or similar.

like image 56
Martin Geisler Avatar answered Sep 18 '22 06:09

Martin Geisler