Java – convert data URL to bufferedimage
I have a data URL for an image file and must pass it to another function Along the path from the data URL to the buffered image, it needs to be a bytearray
My approach is as follows:
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(); }
The problem is that it always throws an unknownimageformatexception exception, which means inputimage is null, which means imageio Read does not recognize imagetype
I use imageio Getreaderformatnames() gets the supported file names and the following list:
Supported Formats: jpg,BMP,bmp,JPG,jpeg,wbmp,png,JPEG,PNG,WBMP,GIF,gif
The dataurl I tried to pass is similar to: data: image / PNG; Base64,... Or data: image / JPG; base64,…
As far as I know, those in the list of supported files should be recognized
In this case, inputimage may also be null? More interestingly, how can I solve it?
Solution
As the review has said, the image data is Base64 encoded To retrieve binary data, you must split the type / encoding terminal and then decode the base64 content into binary data
String encodingPrefix = "base64,"; int contentStartIndex = dataUrl.indexOf(encodingPrefix) + encodingPrefix.length(); byte[] imageData = Base64.decodeBase64(dataUrl.substring(contentStartIndex));
I use org. From Apache common codec apache. commons. codec. binary. Base64, other Base64 decoders should also work