我需要向客户端发送一个
base64
编码的字符串。因此,我在服务器上打开并读取图像文件,对其进行编码并将该数据与 image/jpeg
内容类型一起发送到浏览器。
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
,告诉我我收到了正确的标头信息和正确的传输字节值。
如果我以
Content-type: text/plain
的形式发送该数据,则 base64
字符串会显示在浏览器中(如果我直接调用脚本)。将该输出复制并粘贴到 src
元素的 <img>
中会按预期显示图像。
我在这里做错了什么?
解决方案
感谢
Pekka
指出我的错误。您不需要(您不能!)以这种方法将二进制图像数据编码为 base64 字符串。没有base64编码,它就可以工作。
如果将内容类型设置为 image/jpeg,则应该只提供 jpeg 数据,而不要提供 base64 垃圾。但你将结果视为 html。
您正在有效地构建一个数据 uri,这是可以的,但正如您所指出的,只能作为一个 uri。因此,保留内容类型不变(text/html),并且
echo '<img src="data:image/jpeg;base64,'.base64_encode($image_data).'">';
你就可以开始了。
我相信仅使用 php 就可以非常有效地完成...您可以使用下面的函数以 base64 编码数据渲染图像
function binaryImages($imgSrc,$width = null,$height = null){
$img_src = $imgSrc;
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
if(isset($height) && isset($width))
{
echo '<img src="data:image/jpg;base64,'.$img_str.'" height="'.$height.'" width="'.$width.'"/>';
}
else
{
echo '<img src="data:image/jpg;base64,'.$img_str.'"/>';
}
}
如何使用此功能
binaryImages("../images/end.jpg",100,100);
运行函数binaryImages ..第一个参数是图像路径,第二个参数是宽度,然后是高度...高度和宽度是可选的
在这种情况下,没有理由首先对图像数据进行 Base64 编码。您想要发出的是普通的旧图像数据。
只需按原样传递 JPEG 图像即可。
这对我来说有意义的唯一方法是,通过 AJAX 调用获取
generate.php
的输出,并将结果直接放入 src
属性中。这应该可行(虽然不能在 IE < 8, but I'm sure you know that). But if you can call generate.php
中直接作为图像源,但我认为没有必要这样做。
我会推荐它: base64_encode 使用 MIME base64 编码数据
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
通过Ajax中的纯代码发送,尽管此代码仅在您不想直接发送图像而是以base64发送时才有用。
var imgBase64 = htmlImg.src.split(',')[1];//remove extra header from base64
var binaryData = atob(imgBase64);//convert Base64 string to binary data
var arrayBuffer = new ArrayBuffer(binaryData.length);//create an ArrayBuffer to store the binary data
var uint8Array = new Uint8Array(arrayBuffer);//8-bit view (Uint8Array)
for (var i = 0; i < binaryData.length; i++) {//copy the binary data to the Uint8Array
uint8Array[i] = binaryData.charCodeAt(i);
}
// Crea una instancia de XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST","../database/photouser",true);
xhr.setRequestHeader("Content-Type", "application/octet-stream");//header to send binary data
xhr.send(arrayBuffer);//send the binary data
xhr.onload = function () {//callback to data from php file
if (xhr.status === 200) {
console.log(xhr.responseText);//completed successfully
} else {
console.error('Error en la solicitud');//error in the request
}
};
fileInput.value="";
},100);
通常,当生成图像并尝试通过 Ajax 发送它时,我们必须转换该图像(如果它是 base64 格式)并将其转换为 blob,
htmlImg.src.split(',')[1]
去掉“data:image/jpeg;base64”这部分,只保留格式,避免发送时出错,在php中收集如下:
//Gets the binary data from the blob
$rawData = file_get_contents("php://input");
$file = fopen("../images/users/nombre_image.jpeg", "wb");//create the file
$content = fwrite($file, $rawData);//print the data inside the file
fclose($file);//close the process
if($file == true) echo "exitoso";else echo "no se pudo";
虽然我必须补充一点,浏览器不允许尝试直接以 Base64 发送,因为它们有字符限制,所以显然图像将直接发送或以 blob 形式发送以在 PHP 中处理它。