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?
Asked
Active
Viewed 9.1k times
17
-
1Have a look at the answers here: https://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java – Florent Bayle Sep 10 '14 at 11:00
-
You mean, how do you decode a Base64 string?? – Hot Licks Sep 10 '14 at 11:43
-
1the link provided by @FlorentBayle, helped me. Thankx. I wanted to find the content type of a file which is downloaded from a remote location. – dinesh707 Sep 10 '14 at 11:53
6 Answers
7
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];
===========================================
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];

Muhammad Tahir
- 2,351
- 29
- 25
-
1As mentioned in https://stackoverflow.com/a/41219153/320417, you cannot rely on matching the mime-type at the beginning of the string to verify the file extension. A browser may append the wrong type based on the file's extension (e.g. worksheet.xslx.pdf will be reported as a PDF, even if the file is an excel spreadsheet). – villecoder Nov 17 '22 at 15:32
4
You can check like this:
String[] strings = base64String.split(",");
String extension;
switch (strings[0]) {//check image's extension
case "data:image/jpeg;base64":
extension = "jpeg";
break;
case "data:image/png;base64":
extension = "png";
break;
default://should write cases for more images types
extension = "jpg";
break;
}

Suman
- 74
- 4
3
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){
}
}

user247702
- 23,641
- 15
- 110
- 157

Half Ass Dev
- 398
- 1
- 3
- 12
2
/**
* Extract the MIME type from a base64 string
* @param encoded Base64 string
* @return MIME type string
*/
private static String extractMimeType(final String encoded) {
final Pattern mime = Pattern.compile("^data:([a-zA-Z0-9]+/[a-zA-Z0-9]+).*,.*");
final Matcher matcher = mime.matcher(encoded);
if (!matcher.find())
return "";
return matcher.group(1).toLowerCase();
}
Usage:
final String encoded = "data:image/png;base64,iVBORw0KGgoAA...5CYII=";
extractMimeType(encoded); // "image/png"
extractMimeType("garbage"); // ""

naXa stands with Ukraine
- 35,493
- 19
- 190
- 259
-1
This code is using regex pattern to extract mime type from Base64 string. Though it's written in JavaScript, you can try to implement the same thing in Java.
function base64Mime(encoded) {
var result = null;
if (typeof encoded !== 'string') {
return result;
}
var mime = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);
if (mime && mime.length) {
result = mime[1];
}
return result;
}
Usage:
var encoded = 'data:image/png;base64,iVBORw0KGgoAA...5CYII=';
console.log(base64Mime(encoded)); // "image/png"
console.log(base64Mime('garbage')); // null
Source: miguelmota/base64mime (GitHub)

naXa stands with Ukraine
- 35,493
- 19
- 190
- 259
-1
I did just this: (file is my base64 string)
int extentionStartIndex = file.indexOf('/');
int extensionEndIndex = file.indexOf(';');
int filetypeStartIndex = file.indexOf(':');
String fileType = file.substring(filetypeStartIndex + 1, extentionStartIndex);
String fileExtension = file.substring(extentionStartIndex + 1, extensionEndIndex);
System.out.println("fileType : " + fileType);
System.out.println("file Extension :" + fileExtension);

fatih bayhan
- 21
- 3