12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- package com.huimv.wine.utils;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.util.Base64;
-
- public class Base64ImageSaver {
-
- public static String saveBase64(String base64Image, String filePath) {
- // 分割Base64字符串为两部分:头部信息和编码数据
- String[] parts = base64Image.split(",", 2);
- if (parts.length != 2) {
- throw new IllegalArgumentException("Invalid Base64 image string format");
- }
- String contentType = parts[0];
- String base64Data = parts[1];
-
- // 解码Base64数据
- byte[] decodedBytes = Base64.getDecoder().decode(base64Data);
-
- // 提取文件扩展名
- String ext = contentType.split("/")[1].split(";")[0];
-
- // 拼接完整的文件路径,包括扩展名
- Path filePathWithExt = Paths.get(filePath).resolve(filePath + "." + ext);
-
- try {
- // 将解码后的数据写入文件
- Files.write(filePathWithExt, decodedBytes);
- } catch (IOException e) {
- // 处理文件写入错误
- e.printStackTrace();
- return "文件存储失败: " + e.getMessage();
- }
-
- // 如果一切顺利,返回保存的文件路径
- return filePathWithExt.toString();
- }
-
- public static void main(String[] args) {
- String base64Image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAAAAAAD/2wBDAAUDBAQEAwUEBAQFBgcGBggHBwcICxIB..."; // 示例Base64编码的图像字符串
- String filePath = "path/to/save/image"; // 不包括扩展名的文件路径
-
- String result = saveBase64(base64Image, filePath);
- System.out.println(result); // 打印保存的文件路径或错误信息
- }
- }
|