如何使用php输出图像并下载 [英] How to output image and download using php

查看:72
本文介绍了如何使用php输出图像并下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用php渲染/输出图像并强制下载,而无需将图像保存到服务器?

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

我看过 http://php.net/manual/zh/function.imagejpeg.php 并可以使用 imagejpeg();

我尝试创建到服务器上已保存图像的超链接,并使用 download 强制进行下载.

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?

推荐答案

您可以使用 imagejpeg()将图像输出到浏览器.(文档)

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

当您省略 imagejpeg()的第二个参数或将其设置为 null 时,图像将以二进制形式发送到浏览器.

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"');

这告诉浏览器,它应该将文件下载为 YourFilenameHere.jpg .

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

这篇关于如何使用php输出图像并下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆