I get a file which is Base64 encoded string as the image. But I think the content of this contains information about file type like png, jpeg, etc. How can I detect that? Is there any library which can help me here?
Binary file encoded using base64 encoding; often used to convert text data into base64 data; enables more reliable transmission of e-mail attachments and other information; similar to a . MIME attachment.
In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.
To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.
if you want to get Mime type use this one
const body = {profilepic:"data:image/png;base64,abcdefghijklmnopqrstuvwxyz0123456789"};
let mimeType = body.profilepic.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)[0];
online Demo here
===========================================
if you want to get only type of it like (png, jpg) etc
const body2 = {profilepic:"data:image/png;base64,abcdefghijklmnopqrstuvwxyz0123456789"};
let mimeType2 = body2.profilepic.match(/[^:/]\w+(?=;|,)/)[0];
online Demo here
I have solved my problem with using mimeType = URLConnection.guessContentTypeFromStream(inputstream);
{ //Decode the Base64 encoded string into byte array
// tokenize the data since the 64 encoded data look like this "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAKAC"
String delims="[,]";
String[] parts = base64ImageString.split(delims);
String imageString = parts[1];
byte[] imageByteArray = Base64.decode(imageString );
InputStream is = new ByteArrayInputStream(imageByteArray);
//Find out image type
String mimeType = null;
String fileExtension = null;
try {
mimeType = URLConnection.guessContentTypeFromStream(is); //mimeType is something like "image/jpeg"
String delimiter="[/]";
String[] tokens = mimeType.split(delimiter);
fileExtension = tokens[1];
} catch (IOException ioException){
}
}
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