I have an image that is base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.
Specifically in Commons Codec: class Base64
to decode(byte[] array)
or encode(byte[] array)
No need to use commons--Sun ships a base64 encoder with Java. You can import it as such:
import sun.misc.BASE64Decoder;
And then use it like this:
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
Where encodedBytes
is either a java.lang.String
or a java.io.InputStream
. Just beware that the sun.*
classes are not "officially supported" by Sun.
EDIT: Who knew this would be the most controversial answer I'd ever post? I do know that sun.* packages are not supported or guaranteed to continue existing, and I do know about Commons and use it all the time. However, the poster asked for a class that that was "included with Sun Java 6," and that's what I was trying to answer. I agree that Commons is the best way to go in general.
As an alternative to sun.misc.BASE64Decoder or non-core libraries, look at javax.mail.internet.MimeUtility.decode().
example : Encode/Decode to/from Base64
As of v6, Java SE ships with JAXB. javax.xml.bind.DatatypeConverter has static methods that make this easy. See parseBase64Binary() and printBase64Binary().
No matter what type of app your using (experiment or not), it's just as simple as creating a single Base64.java file in your utils package using the code here:
http://migbase64.sourceforge.net/
Look at the performance charts and notice the difference: 4-5 times as fast.