As I've said elsewhere, in Java, String
is for text, and byte[]
is for binary data.
String ≠ byte[]
Text ≠ Binary Data
An image is binary data. Base64 is an encoding which allows transmission of binary data over US_ASCII compatible text channels (there is a similar encoding for supersets of ASCII text: Quoted Printable).
So, it goes like:
Image (binary data) → Image (text, Base64 encoded binary data) → Image (binary data)
where you would use String encodeBase64String(byte[])
to encode, and byte[] decode(String)
to decode. These are the only sane API's for Base64, byte[] encodeBase64(byte[])
is misleading, the result is US_ASCII-compatible text (so, a String
, not byte[]
).
Now, text has a charset and an encoding, String
uses a fixed Unicode/UTF-16 charset/encoding combination internally, and you have to specify a charset/encoding when converting something from/to a String
, either explicitly, or implicitly, using the platform's default encoding (which is what PrintStream.println()
does). Base64 text is pure US_ASCII, so you need to use that, or a superset of US_ASCII. org.apache.commons.codec.binary.Base64
uses UTF8, which is a superset of US_ASCII, so all is well. (OTOH, the internal java.util.prefs.Base64
uses the platform's default encoding, so I guess it would break if you start your JVM with, say, an UTF-16 encoding).
Back on topic: you've tried to print the decoded image (binary data) as text, which obviously hasn't worked. PrintStream
has write()
methods that can write binary data, so you could use those, and you would get the same garbage as if you wrote the original image. It would be much better to use a FileOutputStream
, and compare the resulting file with the original image file.