将数据 URL 转换为 BufferedImage [英] Convert Data-URL to BufferedImage

查看:53
本文介绍了将数据 URL 转换为 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 Exception,这意味着 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() 来获取支持的文件名并得到以下列表:

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,...data: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 为空?更有趣的是,我该如何解决?

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

我使用来自 apaches common-codec 的 org.apache.commons.codec.binary.Base64,其他 Base64 解码器应该也能工作.

I use org.apache.commons.codec.binary.Base64 from apaches common-codec, other Base64 decoders should work as well.

这篇关于将数据 URL 转换为 BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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