将Data-URL转换为BufferedImage [英] Convert Data-URL to BufferedImage
问题描述
我有一个来自图像文件的数据URL,必须将其传递给另一个函数。沿着从Data-URL到BufferedImage的这条路径,它需要是一个byteArray。
I have a Data-URL from an image file and have to pass it through to another function. Along this path from Data-URL to the BufferedImage it needs to be a 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无法识别图像类型。
The problem is, it always throws the UnknownImageFormatException Exception, which means inputImage is null, which means, the ImageIO.read did not recognize the imagetype.
我使用ImageIO.getReaderFormatNames()来获取支持的文件名,并得到以下列表: / p>
I've used ImageIO.getReaderFormatNames() to get the supported Filenames and got the following list:
Supported Formats:
jpg, BMP, bmp, JPG, jpeg, wbmp, png, JPEG, PNG, WBMP, GIF, gif
我尝试传递的dataURL如下: data:image / png; base64,...
或数据:image / jpg; base64,...
The dataURLs I try to pass are like: data:image/png;base64,...
or data:image/jpg;base64,...
据我所知,这些都在支持的文件列表中,因此应该被识别。
As far as I understand, those are in the supported filelist and therefor should be recognized.
在这种情况下还有什么可能导致inputImage为null ?更有趣的是,我该如何解决呢?
What else could cause the inputImage to be null in this case? And more interesting, how do I solve it?
推荐答案
由于评论已经说明图像数据是Base64编码的。要检索二进制数据,您必须删除类型/编码标头,然后将Base64内容解码为二进制数据。
As the comments already said the image data is Base64 encoded. To retrieve the binary data you have to strip the type/encoding headers, then decode the Base64 content to binary data.
String encodingPrefix = "base64,";
int contentStartIndex = dataUrl.indexOf(encodingPrefix) + encodingPrefix.length();
byte[] imageData = Base64.decodeBase64(dataUrl.substring(contentStartIndex));
我使用 org.apache.commons.codec.binary.Base64 来自apaches common-codec的code>,其他Base64解码器也可以正常工作。
I use org.apache.commons.codec.binary.Base64
from apaches common-codec, other Base64 decoders should work as well.
这篇关于将Data-URL转换为BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!