Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image type from base64 encoded src string

Tags:

WHAT I REQUIRE

My image src looks like this

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...

How can I extract the image type ie; jpeg from the above src given. I am using PHP and the image type cacn also be png and gif.

like image 422
Developer Avatar asked Sep 06 '13 12:09

Developer


People also ask

How do I get an image from Base64 to URL?

One way to convert an image file into a base64 string is to put it into a canvas. Then we can call the canvas's toDataURL method to convert it into a base64 string. We create the getBase64Image function that takes the url string for the URL of the image. Then we create an img eklement with the Image constructor.

How do I view Base64 encoded images?

Use the img Tag to Display Base64 Image in HTML We can specify the URL of the image in the src attribute of the img tag. We can display base64 images by providing the information about the image in the src attribute. We need to define the accurate content type, content-encoding, and charset in the src attribute.

How do I get the Base64 image extension?

To get the extension of an base64 image with JavaScript, we can split the base64 string by the semicolon with split . Then we get the first item from that. And, then we call split again to split the returned string by the / . Then we get the file extension by taking the 2nd element from the returned result.

How can I get MIME type from Base64?

'function guessImageMime(data){ if(data. charAt(0)=='/'){ return "image/jpeg"; }else if(data. charAt(0)=='R'){ return "image/gif"; }else if(data. charAt(0)=='i'){ return "image/png"; } }' Thanks for your answer.


1 Answers

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
like image 158
Boris Guéry Avatar answered Sep 21 '22 15:09

Boris Guéry