【问题标题】:Base64 String to byte[] in java [duplicate]Java中的Base64字符串到字节[] [重复]
【发布时间】:2017-06-15 13:39:24
【问题描述】:

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

java.lang.IllegalArgumentException: 非法 base64 字符 3a

我尝试了以下选项 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);*/`

【问题讨论】:

    标签: java string base64 byte encoder-decoder


    【解决方案1】:

    您可以使用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();
            }
        }
    }
    

    【讨论】:

    • 不错的解决方案!请记住,如果 Web 浏览器以 Base64 格式发布图像,则应考虑字符串 data:image/jpeg;base64, 的开头。你可以使用new String(base64Image.substring(base64Image.indexOf(",") + 1)).getBytes("UTF-8"));
    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 2016-03-28
    • 2010-10-26
    • 1970-01-01
    • 2019-02-22
    • 2014-12-22
    相关资源
    最近更新 更多