Java 如何通过图像的 Base64 编码字符串识别文件类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25763533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:05:14  来源:igfitidea点击:

How to identify file type by Base64 encoded string of a image

javaimagemime-types

提问by dinesh707

I get a file which is Base64encoded 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?

我得到一个文件,它是Base64编码的字符串作为图像。但我认为它的内容包含有关 png、jpeg 等文件类型的信息。我该如何检测?有什么图书馆可以帮助我吗?

采纳答案by Half Ass Dev

I have solved my problem with using mimeType = URLConnection.guessContentTypeFromStream(inputstream);

我已经解决了我使用的问题 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){

    }
}

回答by naXa

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.

此代码使用正则表达式模式从 Base64 字符串中提取 MIME 类型。尽管它是用 JavaScript 编写的,但您可以尝试用 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)

来源:miguelmota/base64mime (GitHub)

回答by fatih bayhan

I did just this: (file is my base64 string)

我就是这样做的:(文件是我的 base64 字符串)

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

回答by naXa

/**
 * 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"); // ""

回答by Muhammad Tahir

if you want to get Mime type use this one

如果你想获得 Mime 类型,请使用这个

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

============================================

如果您只想获取类型它像(png,jpg)等

const body2 = {profilepic:"data:image/png;base64,abcdefghijklmnopqrstuvwxyz0123456789"};
let mimeType2 = body2.profilepic.match(/[^:/]\w+(?=;|,)/)[0];

online Demo here

在线演示在这里

回答by Suman

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