base64与图片文件之间的互转工具类

作者: java 发布时间: 2022-12-29 浏览: 989 次 编辑

通常网络传输图片采用base64 格式,因此在编程时遇到了药将图片文件读取成base64 的格式,和将base64格式的字符串转化为图片的情况

下面是我写的工具类

注:base64转图片时需要先去掉前缀

package com.sharetime.util;

import com.ctc.wstx.util.StringUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @Author: yd
 * @Date: 2018/7/29 11:05
 * @Version 1.0
 */
public class Base64Utils {


    /**
     * 将图片文件转换成base64字符串,参数为该图片的路径
     *
     * @param imageFile
     * @return java.lang.String
     */
    public String ImageToBase64(String imageFile) {
        InputStream in = null;
        byte[] data = null;

        // 读取图片字节数组
        try {
            in = new FileInputStream(imageFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();

        if (data != null) {
            return "data:image/jpeg;base64," + encoder.encode(data);// 返回Base64编码过的字节数组字符串
        }
        return null;
    }

    /**
     * 将base64解码成图片并保存在传入的路径下
     * 第一个参数为base64 ,第二个参数为路径
     *
     * @param base64, imgFilePath
     * @return boolean
     */
    public boolean Base64ToImage(String base64, String imgFilePath) {
        // 对字节数组字符串进行Base64解码并生成图片
        if (base64 == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 用来测试工具类是否成功
     *
     * @param args
     * @return void
     */
    public static void main(String[] args) {
        String path = "C:/Users/YD/Pictures/1.jpg";
        Base64Utils base64Utils = new Base64Utils();
        String s = base64Utils.ImageToBase64(path);
        System.out.println(s);
        String newpath = "C:/Users/YD/Pictures/asd.jpg";
        boolean b = base64Utils.Base64ToImage(s, newpath);
        System.out.println(b);
    }

} 

注:还需要注意的一点是,在网站上src=base64的格式也可以将图片显示出来,但是在图片的前面需要加入标识data:image/jpeg;base64

因此在服务端获取到网页传过来的base64字符串时要注意是否包含前缀如果包含前缀则需要去掉在进行转换

image为从网络传过来的base64格式的字符串

int i = image.indexOf("base64,")+7;//获取前缀data:image/gif;base64,的坐标
String newImage = image.substring(i, image.length());//去除前缀