我有一张图片文件的 Data-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为空,也就是说,ImageIO.read无法识别图像类型。
我已经使用了ImageIO.getReaderFormatNames()获取支持的文件名列表,得到以下列表:
Supported Formats:
jpg, BMP, bmp, JPG, jpeg, wbmp, png, JPEG, PNG, WBMP, GIF, gif
我尝试传递的dataURLs格式如下:data:image/png;base64,...
或者 data:image/jpg;base64,...
据我了解,这些是受支持的文件格式,应该可以识别。
除此之外,还有什么原因会导致输入图像(inputImage)为空呢?更有趣的是,我该如何解决它?
DatatypeConverter
将base 64字符串转换回byte[]
。 - Andrew Thompson