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

}
相关推荐
xqqxqxxq25 分钟前
背单词软件技术笔记(V2.0扩展版)
java·笔记·python
消失的旧时光-194334 分钟前
深入理解 Java 线程池(二):ThreadPoolExecutor 执行流程 + 运行状态 + ctl 原理全解析
java·开发语言
哈哈老师啊38 分钟前
Springboot学生综合测评系统hxtne(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot
4311媒体网42 分钟前
帝国cms调用文章内容 二开基本操作
java·开发语言·php
zwxu_1 小时前
Nginx NIO对比Java NIO
java·nginx·nio
可观测性用观测云2 小时前
Pyroscope Java 接入最佳实践
java
气π3 小时前
【JavaWeb】——(若依 + AI)-基础学习笔记
java·spring boot·笔记·学习·java-ee·mybatis·ruoyi
阿里云云原生3 小时前
AgentScope Java 1.0:从模型到应用,AI Agent 全生命周期管理利器!
java·云原生
running up3 小时前
Maven依赖管理和项目构建工具
java·maven
老华带你飞4 小时前
列车售票|基于springboot 列车售票系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·spring