2011-03-22 68 views
1

我有一大串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'); 

?> 

回答

0

内容长度必须指定实际(解码的)内容长度,而不是base64编码数据的长度。

虽然我不知道,修复它会解决这个问题...

+1

这是很好的知道,但是,你是对的,它不能解决问题。 – zvineyard 2011-03-22 14:55:39

2

由于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字符串,这将等同于工作一次解码这一切。

+0

这看起来很有希望!你有更好的PHP例子吗? – zvineyard 2011-03-22 15:00:04

+0

@zvineyard:不是。我会说这可以直接使用'substr()','base64_decode()'和'echo'转换为PHP。 – Piskvor 2011-03-22 15:02:13

+0

您如何看待我刚刚发布的答案? – zvineyard 2011-03-22 15:42:45

1

好的,这是更接近的分辨率。虽然这似乎是以更小的块来解码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'); 
?> 
+0

看起来没问题。您可能要事先计算图像长度(IIRC'4/3 * $ encoded_length'),并在收到解码数据时回显解码数据,而不是缓存到'$ data'中。 – Piskvor 2011-03-22 16:12:39

+0

好点。我用您推荐的更改修补了脚本,但仍然没有获得图像。我只能认为我的base64字符串必须无效。你怎么看? – zvineyard 2011-03-22 16:17:47

+0

我从帖子中获取我的base64数据。它需要被urlencoded吗? – zvineyard 2011-03-22 16:30:09

-1

以base64串保存至使用imagejpeg()或图像文件的不同格式的正确功能,然后用一个简单的标签<img>显示图像。

相关问题