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.
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.
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.
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.
'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.
Well you have basically two options:
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];
Use getimagesize()
and it's equivalent for string:
$info = getimagesizefromstring(explode(',', base64_decode($data)[1], 2));
// $info['mime']; contains the mimetype
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With