17

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?

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
dinesh707
  • 12,106
  • 22
  • 84
  • 134

6 Answers6

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];

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

Muhammad Tahir
  • 2,351
  • 29
  • 25
  • 1
    As 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);