17

I have an upload Api that as a response object delivers (along with other stuff inside a Json object) a base64 encoded jpeg image.

I create the encoded image as so:

$im; // gd image resource
ob_start();
imagejpeg($im);
$data = base64_encode(ob_get_clean());

The data then is put inside a form field using javascript and submitted.

How can I create a GD resource from that again so that I actually can save that image as a file?

Everything in PHP.

elitalon
  • 9,191
  • 10
  • 50
  • 86
The Surrican
  • 29,118
  • 24
  • 122
  • 168

3 Answers3

34

You can use imagecreatefromstring() function:

$data = base64_decode($_POST['image_as_base64']);

$formImage = imagecreatefromstring($data);

"String" does not mean a "real" string. In that case it means bytes/blob data.

13

How can I create a GD resource from that again so that I actually can save that image as a file?

Are you sure you need to do that extra step? How about:

file_put_contents('MyFile.jpg', base64_decode($_POST['MyFormField']));
Vilx-
  • 104,512
  • 87
  • 279
  • 422
  • 1
    yeah, looks the best way ;) my mind was somehow blocked :D +1 but gonna accept the other answer because it was a directa answer to my q – The Surrican Dec 31 '10 at 20:51
  • 1
    @Joe Hopfgartner - Harrumph! Well, a Happy New Year to you anyway, whenever that is for you. :D – Vilx- Dec 31 '10 at 20:59
  • sometimes this step doesn't cut it. TCPDF some software I use chocked on this but worked with GD – Dennis Aug 15 '14 at 13:35
0

I did by this way:

// input is in format: data:image/png;base64,...
$str="data:image/png;base64,"; 
$data=str_replace($str,"",$_POST['image']); 
$data = base64_decode($data);
file_put_contents('tmp/'.mktime().'.png', $data);
Sarvar Nishonboyev
  • 12,262
  • 10
  • 69
  • 70