如何通过图像的Base64编码字符串识别文件类型 [英] How to identify file type by Base64 encoded string of a image

查看:340
本文介绍了如何通过图像的Base64编码字符串识别文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

    }
}

这篇关于如何通过图像的Base64编码字符串识别文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆