base64和图片的转换

/**
 * 将图片转为base64
 * @param filePath
 * @return
 */
    public static String encodeImage(String filePath) {
        BufferedInputStream in = null;
        byte[] data = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            in = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = in.read(buf)) != len) {
                baos.write(buf, 0, len);
            }
            in.close();
            baos.close();
            data = baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("文件读取失败", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("关闭资源流异常", e);
                    in = null;
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    log.error("关闭资源流异常", e);
                    baos = null;
                }
            }

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

    /**
     * 将base64转为图片
     * @param imagebase64
     * @param filePath
     * @return
     */
    public static String decodeImage(String imagebase64, String filePath) {
    BufferedOutputStream os = null;
    byte[] data = null;
    try {
        os = new BufferedOutputStream(new FileOutputStream(filePath));
        data = Base64.decodeBase64(imagebase64);
        os.write(data);
        os.flush();
        os.close();
        return filePath;
    } catch (IOException e) {
        throw new RuntimeException("图片解码失败", e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                log.error("关闭资源异常", e);
                os = null;
            }
        }
    }
}
/**
    Base64转为图片流
 */
    public static byte[] getImgByte(String base64Str) {
        if (base64Str == null) {
            return null;
        }
        try {
            return Base64.decodeBase64(base64Str);
        } catch (IOException e) {
            log.error("解析base64图片异常", e);
            return null;
        }
    }

    /**
     * 图片流装为base64
     * @param fileByte
     * @return
     */
    public static String getImgStrByByte(byte[] fileByte) {
        // 对字节数组进行Base64编码,得到Base64编码的字符串
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(fileByte);

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值