php:从二进制数据重新创建并显示图像
是否可以从二进制数据重新创建图像(如果需要的话进行处理)并显示它们,所有这些都在同一个脚本中?就像
// get and display image 1:
$imagedata1 = file_get_contents('assets/test.png');
$imagedata1 = process_using_gd_or_something($imagedata1);
echo "<img src={$imagedata1} >"; // <-- IS THIS (OR EQUIVALENT) POSSIBLE?
// get and display image 2:
//etc...
我想避免在处理后将图像存储到磁盘并从那里获取它们,或者使用外部脚本......
Is it possible to recreate images from binary data (process them if needed) and display them, all in the same script? Something like
// get and display image 1:
$imagedata1 = file_get_contents('assets/test.png');
$imagedata1 = process_using_gd_or_something($imagedata1);
echo "<img src={$imagedata1} >"; // <-- IS THIS (OR EQUIVALENT) POSSIBLE?
// get and display image 2:
//etc...
I want to avoid storing the images to to disk after processing and getting them from there, or using an external script...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用图像
src
属性中的数据 URI 来执行此操作。格式为:
data:[][;charset=""][;base64],
此示例直接来自 有关数据 URI 的维基百科页面:
You can do this using a data URI in the image
src
attribute.The format is:
data:[<MIME-type>][;charset="<encoding>"][;base64],<data>
This example is straight from the Wikipedia page on data URIs:
这实际上可以使用内联图像(称为数据URIs)。
您的图像标签看起来像这样:
为什么它们大多不是一个好主意:
页面加载将减慢,因为需要获取图像在可以加载并呈现完整的 HTML 结构之前。如果您要对图像执行其他操作,则更是如此。您的网站很可能会感觉比外部图像慢得多。
内联图像需要进行 Base64 编码,大小增加 33%。
如果您正在谈论一个合理的高流量公共网站,我建议您将图像存储在外部并缓存它们。如果只是一个小项目,内联图像可能适合您。
This is actually possible using inline images (called data URIs).
Your image tag would look something like this:
Why they are mostly not a good idea:
Page load will be slowed down because the image needs to be fetched before the full HTML structure can be loaded and thus, rendered. Even more so if you are performing additional operations on the image. Your site will very likely feel much slower than if it were an external image.
Inline images need to be base64 encoded, adding 33% to their size.
If you are talking about a reasonable high-traffic, public site, I would recommend you store your image externally, and cache them. If it's just for a small project, inline images may work for you.
您的另一种可能性是创建一个脚本,将图像数据生成到输出并将链接指向它。
image.php
other_pages.php:
编辑:
抱歉,我错过了不需要外部脚本的通知,但此解决方案比将图像编码为 base64 更有效。
Other possibility for you is to create a script producing the image data to the output and direct the link to it.
image.php
other_pages.php:
EDIT:
Sorry, I missed the notice of not wanting an external script, but this solution is more efficient than encoding the image to base64.
试试这个...
Try this...
如果您只想要图像,周围没有任何 html,您可以使用以下内容:
您一定不要忘记 Content-Length 标头,否则它将无法工作。
您可能还想替换 mime_content_type() ,因为根据文档它已被弃用。
In case you just want the image, without any html around it you can use the following:
You must not forget the Content-Length header, otherwise it won't work.
You may also want to replace mime_content_type() as it is deprecated according to the docs.