发送/显示 base64 编码图像 [英] Sending/Displaying a base64 encoded Image

查看:45
本文介绍了发送/显示 base64 编码图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向客户端发送一个 base64 编码字符串.因此,我在服务器上打开并读取一个图像文件,对其进行编码并将该数据与 image/jpeg 内容类型一起发送到浏览器.php 中的示例:

I need to send a base64 encoded string to a client. Therefore, I'm opening and reading an image file on the server, encode it and send that data along with the image/jpeg content-type to the browser. Example in php:

$image      = $imagedir . 'example.jpg';
$image_file = fopen($image, 'r');
$image_data = fread($image_file, filesize($image));

header("Content-type: image/jpeg");
echo 'data:image/jpeg;base64,' . base64_encode($image_data);

客户端,我来电:

var img     = new Image();
img.src     = "http://www.myserver.com/generate.php";
img.onerror = function(){alert('error');}
$(img).appendTo(document.body);

由于某种原因,这不起作用.onerror 总是触发.例如,观看 FireBug Network task 告诉我,我收到了正确的标头信息和传输字节的正确值.

That does not work for some reason. onerror always fires. Watching the FireBug Network task for instance, tells me that I'm receiving the correct header information and a correct value of transfered bytes.

如果我以 Content-type: text/plain 的形式发送该数据,则 base64 字符串会显示在浏览器中(如果我直接调用脚本).将该输出复制并粘贴到 <img> 元素的 src 中会按预期显示图像.

If I send that data as Content-type: text/plain it works, the base64 string is shown in the browser (if I call the script directly). Copying and pasting that output into the src of a <img> element shows the image as expected.

我在这里做错了什么?

解决方案

感谢 Pekka 指出我的错误.您不需要(您不能!)以这种方法将该二进制图像数据编码为 base64 字符串.如果没有 base64 编码,它就可以工作.

Thanks Pekka for pointing me on my mistake. You don't need (you can't!) encode that binary image data as base64 string in that kind of approach. Without base64 encoding, it just works.

推荐答案

在这种情况下,首先没有理由对图像数据进行base64编码.您要发出的是普通的旧图像数据.

In this case, there is no reason to base64 encode the image data in the first place. What you want to emit is plain old image data.

按原样传递 JPEG 图像.

Just pass through the JPEG image as-is.

这对我来说有意义的唯一方法是,如果您通过 AJAX 调用获取 generate.php 的输出,并将结果直接放入 src 属性中.这应该可以工作(尽管在 IE < 8 中不行,但我相信你知道这一点).但是如果你可以直接调用 generate.php 作为图像的源,我看不出有这个必要.

The only way this would make sense to me is if you grabbed the output of generate.php via an AJAX call, and put the result into the src property directly. That should work (although not in IE < 8, but I'm sure you know that). But if you can call generate.php directly as the image's source, I don't see the need for this.

这篇关于发送/显示 base64 编码图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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