2

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.

afuzzyllama
  • 6,538
  • 5
  • 47
  • 64
user385729
  • 1,924
  • 9
  • 29
  • 42

3 Answers3

5

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));
mcrumley
  • 5,682
  • 3
  • 25
  • 33
2

This looks not just base64 but PHP stream wrapper data.

file_put_contents('MyFile.jpg', file_get_contents('data:image/jpg;base64,/...'));
ThW
  • 19,120
  • 3
  • 22
  • 44
0

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

$imageStr = base64_decode($imgData1);
$image = imagecreatefromstring($imageStr);
imagejpeg($image, $somePath);
Madbreaks
  • 19,094
  • 7
  • 58
  • 72