Base64 String to byte[] in java [duplicate]
Asked Answered
N

1

53

I am trying to convert base64 String to byte array but it is throwing following error

java.lang.IllegalArgumentException: Illegal base64 character 3a

I have tried following options userimage is base64 string

byte[] img1 = org.apache.commons.codec.binary.Base64.decodeBase64(userimage);`

/* byte[] decodedString = Base64.getDecoder().decode(encodedString.getBytes(UTF_8));*/
/* byte[] byteimage =Base64.getDecoder().decode( userimage );*/
/* byte[] byteimage =  Base64.getMimeDecoder().decode(userimage);*/`
Norse answered 30/1, 2017 at 11:49 Comment(0)
B
84

You can use java.util.Base64 package to decode the String to byte[]. Below code which I have used for encode and decode.

For Java 8 :

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Example {

    public static void main(String[] args) {
        try {
            byte[] name = Base64.getEncoder().encode("hello World".getBytes());
            byte[] decodedString = Base64.getDecoder().decode(new String(name).getBytes("UTF-8"));
            System.out.println(new String(decodedString));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

For Java 6 :

import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;

public class Main {

    public static void main(String[] args) {
        try {
            byte[] name = Base64.encodeBase64("hello World".getBytes());
            byte[] decodedString = Base64.decodeBase64(new String(name).getBytes("UTF-8"));
            System.out.println(new String(decodedString));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Bony answered 30/1, 2017 at 11:58 Comment(1)
Nice solution! Remember that if a web browser is posting a image as Base64, you should desconsider the beggining of the string data:image/jpeg;base64,. You can use new String(base64Image.substring(base64Image.indexOf(",") + 1)).getBytes("UTF-8"));Olympiaolympiad

© 2022 - 2024 — McMap. All rights reserved.