Java 将base64编码字符串转换为图片工具类

前言

在一些前后端分离项目中,接口方需要前端把图片转换成base64编码字符串,和表单信息一起通过json接口提交。故在后端中,需要对前端传过来的bas64编码字符串转换成图片文件进行存储。

代码

java 复制代码
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.UUID;

/**
 * 图片处理工具
 * @author rocky
 * @date 2024/01/01 17:29
 */
@Slf4j
public class ImageUtils {

    /**
     * 将base64编码字符串转换为图片
     * @param file base64编码
     * @param path 图片存储路径
     * @return String 文件名
     */
    public static String base64ToImage(String file, String path) {
        // 解密
        OutputStream out = null;
        String fileName = UUID.randomUUID().toString() + ".jpg";
        String filePath = path + File.separator + fileName;
        try {
            File image = new File(filePath);
            File parent = image.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            if (!image.exists()) {
                image.createNewFile();
            }
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀 data:image/jpeg;base64,
            file = file.substring(file.indexOf(",", 1) + 1, file.length());
            byte[] b = decoder.decode(file);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            out = new FileOutputStream(image);
            out.write(b);
        } catch (IOException e) {
            log.error("base64转换图片过程中发生异常", e);
            fileName = null;
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    log.error("base64转换图片过程中发生异常", e);
                }
            }
        }
        return fileName;
    }

}
相关推荐
.生产的驴18 分钟前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
猿周LV26 分钟前
JMeter 安装及使用 [软件测试工具]
java·测试工具·jmeter·单元测试·压力测试
晨集28 分钟前
Uni-App 多端电子合同开源项目介绍
java·spring boot·uni-app·电子合同
时间之城30 分钟前
笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
java·spring boot·笔记·spring·excel
椰羊~王小美37 分钟前
LeetCode -- Flora -- edit 2025-04-25
java·开发语言
凯酱1 小时前
MyBatis-Plus分页插件的使用
java·tomcat·mybatis
程序员总部1 小时前
如何在IDEA中高效使用Test注解进行单元测试?
java·单元测试·intellij-idea
oioihoii1 小时前
C++23中if consteval / if not consteval (P1938R3) 详解
java·数据库·c++23
佳腾_1 小时前
【Web应用服务器_Tomcat】一、Tomcat基础与核心功能详解
java·前端·中间件·tomcat·web应用服务器
异常君2 小时前
线程池隐患解析:为何阿里巴巴拒绝 Executors
java·后端·代码规范