Reputation: 1984
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.
Upvotes: 2
Views: 7299
Reputation: 5700
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));
Upvotes: 5
Reputation: 19502
This looks not just base64 but PHP stream wrapper data.
file_put_contents('MyFile.jpg', file_get_contents('data:image/jpg;base64,/...'));
Upvotes: 2
Reputation: 19549
You need to use imagecreatefromstring
and imagejpeg
, here's an example:
$imageStr = base64_decode($imgData1);
$image = imagecreatefromstring($imageStr);
imagejpeg($image, $somePath);
Upvotes: 0