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