发送/显示一个base64连接codeD映像 [英] Sending/Displaying a base64 encoded Image

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

问题描述

我需要一个的base64 连接codeD字符串发送到客户端。所以,我打开和读取服务器上的图像文件,连接code,并与图像/ 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 始终闪光。看着萤火虫网​​络任务例如,告诉我,我收到了正确的头信息和发送的字节数正确的值。

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.

如果我发送的数据内容类型:文本/纯它的工作原理,在的base64 字符串显示在浏览器(如果我直接调用脚本)。复制并粘贴该输出到的src < IMG> 元素显示预期图像

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.

我在做什么错在这里?

解决方案

感谢佩卡指着我对我的错误。你不需要(你不能!)EN code二进制图像数据的那种做法的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在所有编码图像数据吗?我不认为数据:的URI,可以用这样的方式,并没有什么理由。

Why are you base64 encoding the image data at all? I don't think data: URIs can be used this way, and there is no reason to.

为什么不直接穿过JPEG图像原样?我俯瞰的东西吗?

Why not just pass through the JPEG image as-is? Am I overlooking something?

这将是有意义的我,唯一的方法是,如果你抓住了通过Ajax调用 generate.php 的输出,并把结果写入 SRC 属性直接。这应该工作(虽然不是在IE&LT; 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连接codeD映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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