PHP- 无法将 Base64 字符串保存到图像文件

PHP- Failed to save Base64 string to an image file

我必须在我的本地驱动器上保存 base64 文件,但是当我使用 file_put_contents 时图像损坏了。

我可以使用以下标签在我的浏览器中看到图像,但是当我使用 file_put_contents 时它不起作用。

$data = '<img src="data:image/png;base64,'.$image.'"/>';

代码:

$data = '<img src="data:image/png;base64,'.$image.'"/>';
 //$data = str_replace(' ','+',$data);
  $decoded=base64_decode($image);

file_put_contents('/opt/lampp/htdocs/image.png',$decoded);

这是我的编码图像内容: http://pastebin.com/PtzmceJe

您必须删除图像标签并仅使用标签的 src。字符串应如下所示:

data:image/gif;base64,2CiVBORw0KGgoAAAANSUhE

保存base64编码的图片

    <?php
    //explode at ',' - the last part should be the encoded image now
    $exp = explode(',', $data);
    //we just get the last element with array_pop
    $base64 = array_pop($exp);
    //decode the image and finally save it
    $data = base64_decode($base64);
    //take care of your file extension
    $file = 'image.gif';
    //make sure you are the owner and have the rights to write content
    file_put_contents($file, $data);

或者直接使用你已有的$image变量。

    <?php
    //decode the image and finally save it
    $data = base64_decode($image);
    $file = 'data.png';
    //make sure you are the owner and have the rights to write content
    file_put_contents($file, $data);

看来您输入的内容有误:

$data = '<img src="data:image/png;base64,'.$image.'"/>';
//$decoded=base64_decode($data); wrong $data
$decoded=base64_decode($image); //corrent


file_put_contents('/opt/lampp/htdocs/image.png',$decoded);

也可能是写权限问题或者路径问题,试试:

file_put_contents('image.png',$decoded);// if dir having write permission it should work then try with complete path

继续使用您在此处粘贴的 base64 字符串:http://pastebin.com/PtzmceJe 该图像是 GIF。文件名有时很重要,具体取决于图像查看器或 OS..

将您的代码更改为...

$decoded = base64_decode($image);
file_put_contents('/opt/lampp/htdocs/image.gif',$decoded);

.. 它应该适合你。

您可以在此处 http://imgur.com/sWiwYaX 以 GIF 格式查看转换后的输出。