How to save the jpg file from base64 data

血红的双手。 提交于 2019-12-24 00:27:09

问题


I have the base 64 data for my images and I want to save them in my local machine as JPG Files.

My base 64 code starts with

data:image/jpg;base64,/...

I already tried to save it by the following code:

 file_put_contents('MyFile.jpg', base64_decode($imgData1));

But I cannot open the created image; it says "the file appears to be damaged, corrupt, or is too large". Could you please let me know what I'm missing.

Also if you need any more clarification, please let me know which part you need more clarification.


回答1:


Get rid of the prefex before calling base64_decode.

<?php
// get rid of everything up to and including the last comma
$imgData1 = substr($imgData1, 1+strrpos($imgData1, ','));
// write the decoded file
file_put_contents('MyFile.jpg', base64_decode($imgData1));



回答2:


This looks not just base64 but PHP stream wrapper data.

file_put_contents('MyFile.jpg', file_get_contents('data:image/jpg;base64,/...'));



回答3:


You need to use imagecreatefromstring and imagejpeg, here's an example:

$imageStr = base64_decode($imgData1);
$image = imagecreatefromstring($imageStr);
imagejpeg($image, $somePath);


来源:https://stackoverflow.com/questions/19796105/how-to-save-the-jpg-file-from-base64-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!