问题
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