Base64 java图片工具类

 

import org.springframework.util.Assert;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @description: 图片工具类
 * @author: Mr.Fang
 **/

public class ImageUtils {

    /**
     * description: 图片转 base64
     * create by: Mr.Fang
     *
     * @param path 文件路径
     * @return: java.lang.String
     */
    public static String imageToBase64(String path) throws IOException {
        File file = new File(path);
        Assert.isTrue(file.exists(), "文件不存在");
        String name = file.getName();
        String formatName = name.substring(name.indexOf(".") + 1);
        BufferedImage read = ImageIO.read(file);
        // 创建字节流
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        // 将图片写入字节流
        ImageIO.write(read, formatName, byteStream);
        // 字节流转字节数组
        byte[] bytes = byteStream.toByteArray();
        // base64 编码
        String base64 = Base64.getEncoder().encodeToString(bytes).trim();
        // base64 图片
        return String.format("data:image/%s;base64,%s", formatName, base64);
    }

    /**
     * description: 图片转 base64
     * create by: Mr.Fang
     *
     * @param inputStream 输入流
     * @param formatName  文件格式
     * @return: java.lang.String
     */
    public static String imageToBase64(InputStream inputStream, String formatName) throws IOException {
        BufferedImage read = ImageIO.read(inputStream);
        // 创建字节流
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        // 将图片写入字节流
        ImageIO.write(read, formatName, byteStream);
        // 字节流转字节数组
        byte[] bytes = byteStream.toByteArray();
        // base64 编码
        String base64 = Base64.getEncoder().encodeToString(bytes).trim();
        // base64 图片
        return String.format("data:image/%s;base64,%s", formatName, base64);
    }

    /**
     * description: base64 转图片
     * create by: Mr.Fang
     *
     * @param base64
     * @param path   文件输出路径
     * @return: java.lang.String
     */
    public static Boolean base64ToImage(String base64, String path) {
        String[] result = base64.split(",");
        String base64Head = result[0];
        String bytesString = result[1];
        String formatName = base64Head.substring(base64Head.indexOf("/") + 1, base64Head.indexOf(";"));
        // 转字节数组
        byte[] decode = Base64.getDecoder().decode(bytesString.getBytes(StandardCharsets.UTF_8));
        // 创建字节流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(decode);
        BufferedImage read = null;
        try {
            read = ImageIO.read(inputStream);
            return ImageIO.write(read, formatName, new File(String.format("%s.%s", path, formatName)));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

 

posted @ 2023-04-13 14:59  天葬  阅读(145)  评论(0编辑  收藏  举报