How to identify file type by Base64 encoded string

2020-03-04 08:42发布

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?

6条回答
成全新的幸福
2楼-- · 2020-03-04 09:03

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);
查看更多
够拽才男人
3楼-- · 2020-03-04 09:06

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)

查看更多
Anthone
4楼-- · 2020-03-04 09:09

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){

    }
}
查看更多
虎瘦雄心在
5楼-- · 2020-03-04 09:10

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;
}
查看更多
仙女界的扛把子
6楼-- · 2020-03-04 09:21
/**
 * 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"); // ""
查看更多
Animai°情兽
7楼-- · 2020-03-04 09:22

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

查看更多
登录 后发表回答