Detecting Image Type from Base64 String in PHP

Detecting image type from base64 string in PHP

FileInfo can do that for you:

$encoded_string = "....";
$imgdata = base64_decode($encoded_string);

$f = finfo_open();

$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);

Get image type from base64 encoded src string

Well you have basically two options:

  1. Trust the metadata
  2. Type check the image source directly

Option 1:

Probably the quicker way because it only involve splitting string, but it may be incorrect.
Something like:

$data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA.';
$pos = strpos($data, ';');
$type = explode(':', substr($data, 0, $pos))[1];

Option 2:

Use getimagesize() and it's equivalent for string:

$info = getimagesizefromstring(explode(',', base64_decode($data)[1], 2));
// $info['mime']; contains the mimetype

Get the file extension of a base64 encoded string

Here is a one-liner inspired by @msg's answer:

$extension = explode('/', mime_content_type($base64_encoded_string))[1];

Base64 image string into image file using PHP

I figure it out the solution.

        $pathwithfile = 'your file path with image name';//e.g '/uploads/test.jpg'
$ifp = fopen( $pathwithfile, 'wb' );
// split the string on commas // $data[ 0 ] == "data:image/png;base64" // $data[ 1 ] == <actual base64 string> $data = explode( ',', $imagedata ); $success = fwrite( $ifp, base64_decode( $data[ 1 ] ) ); // clean up the file resource fclose( $ifp );

How to save a PNG image server-side, from a base64 data URI

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);

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

And as a one-liner:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

An efficient method for extracting, decoding, and checking for errors is:

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 = str_replace( ' ', '+', $data );
$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);


Related Topics



Leave a reply



Submit