简体   繁体   English

如何使用php输出图像并下载

[英]How to output image and download using php

Is it possible to render/output an image using php and force a download, without saving the image to the server? 是否可以使用php渲染/输出图像并强制下载,而无需将图像保存到服务器?

I've looked at http://php.net/manual/en/function.imagejpeg.php and can render the image and save the image using imagejpeg(); 我看过http://php.net/manual/en/function.imagejpeg.php ,可以渲染图像并使用imagejpeg();保存图像imagejpeg();

I've tried creating a hyperlink to the saved image on the server and forcing a download using download . 我尝试创建到服务器上已保存图像的超链接,并使用download强制进行download

Just wondering if there was a easier/simpler method? 只是想知道是否有一种更简单的方法?

You can use imagejpeg() to output the image to the browser. 您可以使用imagejpeg()将图像输出到浏览器。 ( 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). 当您省略imagejpeg()的第二个参数或将其设置为null ,图像将以二进制形式发送到浏览器。

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 . 这告诉浏览器,它应该将文件下载为YourFilenameHere.jpg

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM