【工具类】Base64位字符串与图片转换

作者: 李玉凯 分类: JAVA 发布时间: 2020-12-28 14:54
package org.jeecg.common.util;

import java.io.*;
import java.util.Base64;

/**
 * Created by 李玉凯
 */
public class ImageBase64Utils {

    /**
     * 将base64位字符串转换成图片
     * @param baseStr        base64图片字符串
     * @param imgFilePath    要保存到图片地址
     * @return boolean
     */
    public static boolean baseStrToImg(String baseStr, String imgFilePath) {
        if (CheckNullUtils.isNull(baseStr)) {// 图像数据为空
            return false;
        }
        try {
            // Base64解码
            byte[] bytes = Base64.getDecoder().decode(baseStr);
            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;
        }
    }

    /**
     * 将图片转换成base64位字符串
     * @param imgFilePath 图片路径
     * @return String
     */
    public static String imgToBaseStr(String imgFilePath) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return Base64.getEncoder().encodeToString(data); // 返回Base64编码过的字节数组字符串
    }

}

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

邮箱地址不会被公开。 必填项已用*标注

17 + = 25