我有一个来自图像文件的数据 URL,必须将它传递给另一个函数。沿着这条从 Data-URL 到 BufferedImage 的路径,它需要是一个 byteArray。
我的方法如下:
String dataUrl;
byte[] imageData = dataUrl.getBytes();
// pass the byteArray along the path
// create BufferedImage from byteArray
BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(imageData));
// If the picture is null, then throw an unsupported image exception.
if (inputImage == null) {
throw new UnknownImageFormatException();
}
问题是,它总是抛出 UnknownImageFormatException 异常,这意味着 inputImage 为 null,这意味着 ImageIO.read 无法识别图像类型。
我使用 ImageIO.getReaderFormatNames() 获取支持的文件名并获得以下列表:
Supported Formats:
jpg, BMP, bmp, JPG, jpeg, wbmp, png, JPEG, PNG, WBMP, GIF, gif
我尝试传递的 dataURL 如下:data:image/png;base64,...
或 data:image/jpg;base64,...
据我所知,这些在受支持的文件列表中,因此应该被识别。
在这种情况下,还有什么可能导致 inputImage 为空?更有趣的是,我该如何解决?
最佳答案
正如评论所说,图像数据是 Base64 编码的。要检索二进制数据,您必须去除类型/编码 header ,然后将 Base64 内容解码为二进制数据。
String encodingPrefix = "base64,";
int contentStartIndex = dataUrl.indexOf(encodingPrefix) + encodingPrefix.length();
byte[] imageData = Base64.decodeBase64(dataUrl.substring(contentStartIndex));
我使用来自 apaches common-codec 的 org.apache.commons.codec.binary.Base64
,其他 Base64 解码器应该也能正常工作。
关于java - 将数据 URL 转换为 BufferedImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18569591/