Reputation: 1
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?
Upvotes: 0
Views: 3400
Reputation: 1500225
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:
DatatypeConverter.parseBase64
isn'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)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?
Upvotes: 1