如何将大量的base64图像数据转换回带有PHP的图像?
问题描述:
我有一大串base64图像数据(大约200K)。当我尝试通过输出具有正确标题的解码数据来转换该数据时,脚本死亡,好像内存不足。我的Apache日志中没有错误。下面的示例代码适用于小图片。如何解码大图像?如何将大量的base64图像数据转换回带有PHP的图像?
<?php
// function to display the image
function display_img($imgcode,$type) {
header('Content-type: image/'.$type);
header('Content-length: '.strlen($imgcode));
echo base64_decode($imgcode);
}
$imgcode = file_get_contents("image.txt");
// show the image directly
display_img($imgcode,'jpg');
?>
答
内容长度必须指定实际(解码的)内容长度,而不是base64编码数据的长度。
虽然我不知道,修复它会解决这个问题...
答
由于base64 -encoded数据分离干净,每4个字节(即3个字节明文编码为4个字节的Base64编码文本),你可以在你的B64字符串分割成4个字节的倍数,并分别对其进行处理:
while (not at end of string) {
take next 4096 bytes // for example - 4096 is 2^12, therefore a multiple of 4
// you could use much larger blocks, depends on your memory limits
base64-decode them
append the decoded result to a file, or a string, or send it to the output
}
如果你有一个有效的base64字符串,这将等同于工作一次解码这一切。
答
好的,这是更接近的分辨率。虽然这似乎是以更小的块来解码base64数据,但我仍然没有在浏览器中获得图像。如果我在放置标题之前回显数据,我会得到输出。再次,这与一个小图像,但不是一个大的作品。思考?
<?php
// function to display the image
function display_img($file,$type) {
$src = fopen($file, 'r');
$data = "";
while(!feof($src)) {
$data .= base64_decode(fread($src, 4096));
}
$length = strlen($data);
header('Content-type: image/'.$type);
header('Content-length: '.$length);
echo $data;
}
// show the image directly
display_img('image.txt','jpg');
?>
答
以base64串保存至使用imagejpeg()
或图像文件的不同格式的正确功能,然后用一个简单的标签<img>
显示图像。
这是很好的知道,但是,你是对的,它不能解决问题。 – zvineyard 2011-03-22 14:55:39