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;
    }

}
相关推荐
callJJ8 小时前
Spring AI 文本聊天模型完全指南:ChatModel 与 ChatClient
java·大数据·人工智能·spring·spring ai·聊天模型
CBeann8 小时前
企业级规则引擎落地实战:动态脚本引擎 QLExpress ,真香!
java·ai·大模型·规则引擎·qlexpress·大厂实战项目
懈尘8 小时前
从 Java 1.7 到 Java 21:逐版本深入解析新特性与平台演进
java·开发语言
亓才孓8 小时前
[Maven]Maven基础
java·maven
hello 早上好8 小时前
05_Java 类加载过程
java·开发语言
echoVic9 小时前
多模型支持的架构设计:如何集成 10+ AI 模型
java·javascript
橙露9 小时前
Java并发编程进阶:线程池原理、参数配置与死锁避免实战
java·开发语言
echoVic9 小时前
AI Agent 安全权限设计:blade-code 的 5 种权限模式与三级控制
java·javascript
PPPPickup9 小时前
easymall---图片上传以及图片展示
java
历程里程碑9 小时前
Linux 库
java·linux·运维·服务器·数据结构·c++·算法