您的位置 首页 java

一文读懂Base64,Java代码实现

有不对的地方,欢迎指正!一起学习,共同进步。


1、Base64历史

大家都知道,互联网最初是由美国发明的,因此上网使用的都是英文,传输的数据也是英文。在1994年,我国引进互联网,因此如何解决中文上网,数据怎么传输中文,成为了一个难题。为此,Base64就是为了解决这个难题而诞生的,Base64将中文进行 编码 ,转化为可打印字符。

Base64

2、Base64编码原理

假设我们想发送短信给别人,短信内容的编码过程是这样:

  1. 首先对短信内容进行分割,每三个字节一组,一共24个 比特
  2. 其次对24比特的数据进行分割重组,每组6比特。
  3. 对然后对每组6个比特的数据进行填充,即每组最前面添加两个“0”,构成每组8个bit
  4. 最后根据Base64编码表,获取相应的编码值。

官网编码图

3、Base64转为图片,图片转为Base64

 public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组 字符串 ,并对其进行Base64编码处理
         byte [] data = null;

        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in. close ();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[]  bytes  = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }  
 public static void main(String[] args) {
        // 测试从Base64编码转换为图片文件
        String strImge = "";
        GenerateImage(strImge, "D:\11. jpg ");
        // 测试从图片文件转换为Base64编码
       // System.out.println(GetImageStr("d:\11.jpg"));
    }  

最后感谢各位转发+关注,给码仔一点动力。(文章不懂的,可以私信,有问必答)

文章来源:智云一二三科技

文章标题:一文读懂Base64,Java代码实现

文章地址:https://www.zhihuclub.com/171726.shtml

关于作者: 智云科技

热门文章

网站地图