[英]PHP- Failed to save Base64 string to an image file
I have to save base64 file on my local drive, but image corrupted when I have use file_put_contents. 我必须将base64文件保存在本地驱动器上,但是使用file_put_contents时图像损坏。
I am able to see the image in my browser using following tag, but when I am using file_put_contents so it's not working. 我可以使用以下标记在浏览器中查看图像,但是当我使用file_put_contents时,它无法正常工作。
$data = '<img src="data:image/png;base64,'.$image.'"/>';
code: 码:
$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);
here is my encoded image content: http://pastebin.com/PtzmceJe 这是我编码的图像内容: http : //pastebin.com/PtzmceJe
Going on the base64 string you have pasted here: http://pastebin.com/PtzmceJe the image is a GIF. 继续您在此处粘贴的base64字符串: http : //pastebin.com/PtzmceJe图像是GIF。 The filename is sometimes important depending on the image viewer or OS..
文件名有时很重要,具体取决于图像查看器或操作系统。
Change your code to this... 将您的代码更改为此...
$decoded = base64_decode($image);
file_put_contents('/opt/lampp/htdocs/image.gif',$decoded);
.. and it should work for you. ..并且它应该为您工作。
You can see the converted output here http://imgur.com/sWiwYaX as a GIF. 您可以在http://imgur.com/sWiwYaX上以GIF 格式查看转换后的输出。
You have to remove the image tag and only use the src
of the tag. 您必须删除图像标签,而仅使用标签的
src
。 String should look like: 字符串应如下所示:
data:image/gif;base64,2CiVBORw0KGgoAAAANSUhE
数据:image / gif; base64,2CiVBORw0KGgoAAAANSUhE
Saving the base64 encoded image 保存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);
Or directly use the $image
variable you have. 或者直接使用您拥有的
$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);
Seems like you are wiring wrong content: 似乎您接线的内容错误:
$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);
Or it may be write permission issue or path issue, try: 或者它可能是写权限问题或路径问题,请尝试:
file_put_contents('image.png',$decoded);// if dir having write permission it should work then try with complete path
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.