我必须在本地驱动器上保存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
继续您在这里粘贴的base64字符串:http://pastebin.com/PtzmceJe该图像是GIF。文件名有时很重要,这取决于图像查看器或操作系统。
把你的代码改成这样…
$decoded = base64_decode($image);
file_put_contents('/opt/lampp/htdocs/image.gif',$decoded);
. .它应该对你有用。
您可以在这里看到转换后的输出https://i.stack.imgur.com/T43VU.jpg GIF格式
您必须删除图像标记,仅使用标记的src
。字符串应该看起来像:
数据:图像/gif; base64 2 civborw0kggoaaaansuhe
保存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