Uploading A Base64 Encoded String As An Image

3,972 Views

Are you looking for a way to save a PNG image server-side, from a base64 data string, or unable to upload to a base64 encoded image using Codeigniter? We can help you with that.

While you are using Nihilogic’s “Canvas2Image” JavaScript tool to convert canvas drawings to PNG images, if you need to turn the generated base64 strings into actual PNG file in the server in PHP platform,

// Generate the image file

var image = Canvas2Image.saveAsPNG(canvas, true);  

image.id = “canvasimage”;

canvas.parentNode.replaceChild(image, canvas);

var url = ‘hidden.php’,

data = $(‘#canvasimage’).attr(‘src’);

 $.ajax({

type: “POST”,

url: url,

dataType: ‘text’,

data: {

     base64data : data

}

});

The ‘hidden.php’ receives a data block as follows.

“data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE…”

In order to overcome this error, proceed with the following changes.

  • First you have to extract the base64 data from that particular string.
  • Later decode the extracted base64 data and then save it on your disk.
  • You don’t need GD since it is already a PNG file.

$data = ‘data:image/png;base64,AAAFBfj42Pj4’;

 list($type, $data) = explode(‘;’, $data);

list(, $data)  = explode(‘,’, $data);

2$data = base64_decode($data);

 file_put_contents(‘/tmp/image.png’, $data);

As an one liner,

$data = base64_decode(preg_replace(‘#^data:image/w+;base64,#i’, ”, $data));

An efficient method for extracting, decoding and verifying is as follows.

if (preg_match(‘/^data:image/(w+);base64,/’, $data, $type)) {

$data = substr($data, strpos($data, ‘,’) + 1);

$type = strtolower($type[1]); // jpg, png, gif

  if (!in_array($type, [ ‘jpg’, ‘jpeg’, ‘gif’, ‘png’ ])) {

     throw new Exception(‘invalid image type’);

}

  $data = base64_decode($data);

  if ($data === false) {

     throw new Exception(‘base64_decode failed’);

}

} else {

throw new Exception(‘did not match data URI with image data’);

}

file_put_contents(“img.{$type}”, $data);

If you have any difficulty in proceeding with the changes or in the desired output, please feel free to contact us. We provide our multi-dimensional solutions in various technological aspects. Visit our home page in order to know more about us.

3,972 Views

Categories

Archives

Tags