Files
script/src/main/java/com/xiang/common/utils/ImageUtils.java
2026-05-08 09:19:04 +08:00

69 lines
2.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.xiang.common.utils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
/**
* @Author: xiang
* @Date: 2026-05-08 08:56
*/
public class ImageUtils {
/**
* 将 Base64 图片写入文件
* @param base64String Base64 编码的图片字符串
* @param outputPath 输出文件路径
*/
public static void saveBase64Image(String base64String, String outputPath) {
try {
// 处理可能包含前缀的 Base64如 data:image/png;base64,
String base64Data = extractBase64Data(base64String);
// 解码 Base64
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
// 写入文件
try (FileOutputStream fos = new FileOutputStream(outputPath)) {
fos.write(imageBytes);
}
System.out.println("图片已保存至: " + outputPath);
} catch (IllegalArgumentException e) {
System.err.println("Base64 解码失败: " + e.getMessage());
} catch (IOException e) {
System.err.println("文件写入失败: " + e.getMessage());
}
}
/**
* 提取纯 Base64 数据(去除前缀)
*/
private static String extractBase64Data(String base64String) {
if (base64String == null || base64String.isEmpty()) {
throw new IllegalArgumentException("Base64 字符串不能为空");
}
// 检查是否包含 data:image/xxx;base64, 前缀
if (base64String.contains(",")) {
return base64String.split(",", 2)[1];
}
return base64String;
}
/**
* 从 Base64 字符串中获取图片类型
*/
public static String getImageType(String base64String) {
if (base64String.startsWith("data:image/")) {
String type = base64String.substring(11, base64String.indexOf(";"));
return type; // 返回 png, jpeg, gif 等
}
return "png"; // 默认类型
}
public static void main(String[] args) {
}
}