在Java中将Base64字符串转换为byte[]

49

我正在尝试将Base64字符串转换为字节数组,但它抛出以下错误:

java.lang.IllegalArgumentException:非法的Base64字符3a

我尝试了以下选项,userimage是Base64字符串:

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);*/`
1个回答

80
你可以使用 java.util.Base64 软件包将字符串解码为 byte[]。以下是我用于编码和解码的代码。
对于 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();
        }
    }

对于 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();
        }
    }
}

7
好的解决方案!请记住,如果网络浏览器将图像以Base64格式发布,则应忽略字符串开头的data:image/jpeg;base64,。您可以使用new String(base64Image.substring(base64Image.indexOf(",") + 1)).getBytes("UTF-8")) - shimatai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接