Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode Base64 data in Java

Tags:

java

base64

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.

like image 447
Ryan P Avatar asked Jan 22 '09 15:01

Ryan P


2 Answers

As of Java 8, there is an officially supported API for Base64 encoding and decoding. In time this will probably become the default choice.

The API includes the class java.util.Base64 and its nested classes. It supports three different flavors: basic, URL safe, and MIME.

Sample code using the "basic" encoding:

import java.util.Base64;  byte[] bytes = "Hello, World!".getBytes("UTF-8"); String encoded = Base64.getEncoder().encodeToString(bytes); byte[] decoded = Base64.getDecoder().decode(encoded); 

The documentation for java.util.Base64 includes several more methods for configuring encoders and decoders, and for using different classes as inputs and outputs (byte arrays, strings, ByteBuffers, java.io streams).

like image 148
Andrea Avatar answered Oct 06 '22 01:10

Andrea


As of v6, Java SE ships with JAXB. javax.xml.bind.DatatypeConverter has static methods that make this easy. See parseBase64Binary() and printBase64Binary().

UPDATE: JAXB is no longer shipped with Java (since Java 11). If JAXB is required for your project, you will need to configure the relevant libraries via your dependency management system, for example Maven. If you require the compiler (xjc.exe) you also need to download that separately.

like image 32
Jeremy Ross Avatar answered Oct 05 '22 23:10

Jeremy Ross