Sunday, November 19, 2017

How to convert Image to Base64 using Apache Commons?

If you are on v6 or greater you can use DatatypeConverter. Then your code will be look like below.
String base64String = DatatypeConverter.printBase64Binary(baos.toByteArray());
byte[] bytearray = DatatypeConverter.parseBase64Binary(base64String);
Or,
You can also use: java.util.Base64 which is added in Java 1.8
String base64String = new String(Base64.getEncoder().encode(bytesToEncode));
byte[] decordedValue = Base64.getDecoder().decode(base64String);
Or, you can make a method calling procedure in apache commons that is given below
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

public String decode(String s) {
    return StringUtils.newStringUtf8(Base64.decodeBase64(s));
}
public String encode(String s) {
    return Base64.encodeBase64String(StringUtils.getBytesUtf8(s));
}

Resource Link:

  1. org.apache.commons.codec.binary.base64 Example
  2. how to avoid warning for the Base 64?
Original Link: https://stackoverflow.com/a/37431291/2293534

No comments:

Post a Comment