java – 将数据URL转换为BufferedImage
发布时间:2020-12-14 05:07:09 所属栏目:Java 来源:网络整理
导读:我有一个图像文件的数据URL,必须将其传递给另一个功能.沿着Data-URL到Buffered Image的路径,它需要是一个byteArray. 我的做法如下: String dataUrl;byte[] imageData = dataUrl.getBytes();// pass the byteArray along the path// create BufferedImage fr
我有一个图像文件的数据URL,必须将其传递给另一个功能.沿着Data-URL到Buffered
Image的路径,它需要是一个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不能识别imagetype. 我使用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为null?更有趣的是,我该如何解决呢? 解决方法
由于评论已经说过,图像数据是Base64编码的.要检索二进制数据,您必须剥离类型/编码头,然后将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解码器也应该工作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |