Organizational Research By

Surprising Reserch Topic

return a php page as an image

return a php page as an image  using -'php,image-processing,http-headers,mime-types'

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.

asked Sep 30, 2015 by vijayshukla80
0 votes

Related Hot Questions

4 Answers

0 votes

The PHP Manual has this example:

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

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.

answered Sep 30, 2015 by sachin wagh
0 votes

This should work. It may be slower.

$img = imagecreatefromjpeg($filename);
header("Content-Type: image/jpg");
answered Sep 30, 2015 by mcasudhir
0 votes

readfile() is commonly used to perform this task as well. I can't say if it's a better solution than using fpassthru(), but it works well for me and, according to the docs, it will not present any memory issues.

Here's my example of it in action:

if (file_exists("myDirectory/myImage.gif")) {//this can also be a png or jpg

    //Set the content-type header as appropriate
    $imageInfo = getimagesize($fileOut);
    switch ($imageInfo[2]) {
        case IMAGETYPE_JPEG:
            header("Content-Type: image/jpg");
        case IMAGETYPE_GIF:
            header("Content-Type: image/gif");
        case IMAGETYPE_PNG:
            header("Content-Type: image/png");

    // Set the content-length header
    header('Content-Length: ' . filesize($fileOut));

    // Write the image bytes to the client

answered Sep 30, 2015 by shikhar jain
0 votes

Another easy Option (not any better, just different) if you aren't reading from a database is to just use a function to output all the code for you... Note: If you also wanted php to read the image dimensions and give that to the client for faster rendering, you could easily do that too with this method.


    This is my awesome website.

Like my nice picture above?
answered Sep 30, 2015 by vijayshukla80