图片文件和 Base64 字符串互转(Java 实现)

  项目中,有些场景下,客户端需要将本地图片传输到服务方存储,此时客户端可以将图片文件转为 Base64 字符串传输到服务方,服务方收到后再将 Base64 字符串还原为图片。以下是一些图片文件和 Base64 字符串互转的工具类,以及校验图片大小的工具。

一、依赖包
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.5</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>
二、工具类 Java 代码
package com.example.testdemo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

@Slf4j
public class ImageUtil {

    /**
     * 把文件转为 base64
     *
     * @param imagePath 文件全路径名
     * @return base64 字符串
     */
    public static String imageToBase64(String imagePath) {

        try {
            File file = new File(imagePath);
            FileInputStream fis = new FileInputStream(file);
            byte[] imageBytes = new byte[fis.available()];
            fis.read(imageBytes);
            fis.close();
            return Base64.encodeBase64String(imageBytes);
        } catch (IOException e) {
            log.error("图片转 base64 出现异常", e);
            return null;
        }
    }

    /**
     * 把文件转为 base64
     *
     * @param path 文件全路径名
     * @return base64 字符串
     * @throws Exception 抛出异常
     */
    public static String convertBase64(String path) throws Exception {
        if (StringUtils.isBlank(path)) {
            throw new Exception("path is null");
        } else {
            return convertBase64(new File(path));
        }
    }

    /**
     * 文件转为 Base64
     *
     * @param file 文件
     * @return Base64 字符串
     * @throws Exception 抛出异常
     */
    public static String convertBase64(File file) throws Exception {
        if (Objects.isNull(file)) {
            throw new Exception("file is null");
        } else if (!file.exists()) {
            throw new Exception("file does not exist");
        } else {
            byte[] data = FileUtils.readFileToByteArray(file);
            return Base64.encodeBase64String(data);
        }
    }

    /**
     * base64 字符串转图片文件 File
     *
     * @param code base64 字符串
     * @param path 生成图片的全名
     * @return 生成的文件
     * @throws IOException 抛出异常
     */
    public static File base64ToFile(String code, String path) throws IOException {
        File file = new File(path);
        byte[] data = Base64.decodeBase64(code);
        FileUtils.writeByteArrayToFile(file, data);
        return file;
    }

    /**
     * 校验图片的宽度和高度是否符合要求(具体可按实际要求修改判断逻辑)
     *
     * @param path 图片全路径
     * @return 符合要求:true;否则:false
     */
    public static boolean checkImageWidthAndHeight(String path) {
        try {
            File imageFile = new File(path);
            BufferedImage bufferedImage = ImageIO.read(imageFile);

            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            log.info("图片:[{}], 宽度:[{}] 像素, 高度:[{}] 像素", path, width, height);

            // 假如图片要求是正方形,且不低于 300 * 300,不高于 800 * 800
            if (width != height) {
                log.warn("图片不是正方形");
                return false;
            }
            if (width < 300) {
                log.warn("图片低于 300 * 300,不符合要求");
                return false;
            }
            if (width > 800) {
                log.warn("图片高于 800 * 800,不符合要求");
                return false;
            }

            return true;
        } catch (IOException e) {
            log.error("校验图片规格出现异常", e);
            return false;
        }
    }

    public static void main(String[] args) throws Exception {

        try {
            // 校验图片是否符合规范
            String basePath = "D:\\";
            String fileName = "test.jpeg";
            String fullPath = basePath + File.separator + fileName;
            boolean res = checkImageWidthAndHeight(fullPath);
            if (!res) {
                log.warn("图片不符合规范");
            }

            // 图片转 base64
            String base64Str = convertBase64(fullPath);
            log.info("base64 字符串:[{}]", base64Str);

            // base64 字符串转图片文件 File
            // 生成的图片
            String convertPath = basePath + File.separator + "convert.jpg";
            base64ToFile(base64Str, convertPath);

            // 图片转 base64
            log.info("base64 字符串:[{}]", imageToBase64(fullPath));
        } catch (IOException e) {
            log.error("图片转化测试异常", e);
        }
    }
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值