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

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

我用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){ } } 

我这样做了:(文件是我的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); 

此代码使用正则表达式模式从Base64字符串中提取mime类型。 虽然它是用JavaScript编写的,但您可以尝试在Java中实现相同的function。

 function base64MimeType(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; } 

用法:

 var encoded = 'data:image/png;base64,iVBORw0KGgoAA...5CYII='; console.log(base64Mime(encoded)); // "image/png" console.log(base64Mime('garbage')); // null 

来源: miguelmota / base64mime(GitHub)