0

Is it possible to render/output an image using php and force a download, without saving the image to the server?

I've looked at http://php.net/manual/en/function.imagejpeg.php and can render the image and save the image using imagejpeg();

I've tried creating a hyperlink to the saved image on the server and forcing a download using download.

Just wondering if there was a easier/simpler method?

jmiller
  • 578
  • 11
  • 28

2 Answers2

5

You can use imagejpeg() to output the image to the browser. (Docs)

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Output the image
imagejpeg($image);

When you leave out the second parameter of imagejpeg() or set it to null the image will be sent to the browser (in binary form).

To trigger the download in the browser, you need to set another header value:

header('Content-Disposition: attachment; filename="YourFilenameHere.jpg"');

This tells the browser, that it should download the file as YourFilenameHere.jpg.

rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
1

You can also use this code if the file is in another directory:

 $file = 'test.png';
 $filepath = "images/" . $file;


    if(file_exists($filepath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); 
        readfile($filepath);
        exit;
    }
Amir Hajiha
  • 836
  • 8
  • 20