I want to obtain an image from a string coded in base 64.
I'm using this method:
String image = ABAfXWQAQH11kAEB9dZABAfXWQAQH11kAEB9dZABAfXW ...
public void change(){
byte [] image = DatatypeConverter.parseBase64Binary(image);
System.out.println(image+" bytes");
InputStream in = new ByteArrayInputStream(imagen);
System.out.println(in+" inStream");
BufferedImage finalImage= ImageIO.read(in);
System.out.println(finalImage+" buffer");
}
Using that I obtain this output
[B@ca2dce bytes
java.io.ByteArrayInputStream@18558d2 inStream
null buffer
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at MyCLass.change(MyClass.java:48)
at MyClass.<init>(MyClass.java:26)
at MyClass.main(MyClass.java:59)
Why is the bufferedImage null?
1 Answer 1
From the documentation:
If no registered ImageReader claims to be able to read the resulting stream, null is returned.
So my guess is that no registered ImageReader claims to be able to read it...
Assuming your InputStream code doesn't have the typo you've got in your question (imagen instead of image) that leaves three options I can think of easily:
- Your image data was corrupt to start with
- You've encoded it incorrectly into base64
DatatypeConverter.parseBase64isn't quite appropriate for the base64 format you've got. (It's not a converter I've used before. There are lots of options for base64 - e.g. this public domain one)- The data is all fine by the time it reaches
ImageIO.read, but it's not a supported image format.
You should work out which of these is the case - in particular, what happens if you skip the base64 encoding completely? Or what happens if you compare the base64-encoded-then-decoded data with the original? (Is it at least the same length?) If you write out the base64-decoded data to a file, can you open it in your favourite image program?
Base64.decodeBase64to load an image from a Base64 string.