1

I want to save a base64 string as an image (.png or .jpg) on my server.

The string I get looks like this: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQA[...]"

I tried this:

$data = $_POST['form_new_data'];
        list($type, $data) = explode(';', $data);
        list(, $data)      = explode(',', $data);
        $data = base64_decode($data);
        file_put_contents("/userImgs/pic.jpg",$data);

but it is not working (maybe because the base64 string is a jpeg?).. Please help..

nameless
  • 1,483
  • 5
  • 32
  • 78

1 Answers1

7

try this

$data = $_POST['form_new_data'];
file_put_contents('img.jpg', base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data)));
georoot
  • 3,557
  • 1
  • 30
  • 59
  • you forgot stripping the prefix ;-P – bwoebi Sep 07 '15 at 18:52
  • realized after posting it. It is fine now rt? – georoot Sep 07 '15 at 18:53
  • thank you, works, but can you tell me, why mine is not working? I used the code from the accepted answer of this thread: http://stackoverflow.com/questions/11511511/how-to-save-a-png-image-server-side-from-a-base64-data-string @georoot – nameless Sep 07 '15 at 18:56
  • @user3375021 to be frank i am not sure why explode is being used at all. I would say try to print $data in your script just before you store it to a file and compare it with the output of preg_replace in my script – georoot Sep 07 '15 at 19:29
  • Worked beautifully. Thank you! – Mike Carpenter Jun 17 '18 at 22:54