杰瑞科技汇

Java图片转Base64,如何实现?

Java 图片转换为 Base64 编码

在 Java 中,你可以使用多种方法将图片文件转换为 Base64 编码字符串,以下是几种常见的实现方式:

Java图片转Base64,如何实现?-图1
(图片来源网络,侵删)

使用 Java 标准库

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
public class ImageToBase64 {
    public static String convertImageToBase64(String imagePath) throws IOException {
        File file = new File(imagePath);
        try (FileInputStream imageInFile = new FileInputStream(file);
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = imageInFile.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = byteArrayOutputStream.toByteArray();
            // 使用 Base64 编码
            return Base64.getEncoder().encodeToString(imageBytes);
        }
    }
    public static void main(String[] args) {
        try {
            String base64Image = convertImageToBase64("path/to/your/image.jpg");
            System.out.println("Base64 Image: " + base64Image);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用 Java 8 的 Base64 类(更简洁)

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
public class ImageToBase64 {
    public static String convertImageToBase64(String imagePath) throws IOException {
        File file = new File(imagePath);
        byte[] imageBytes = Files.readAllBytes(file.toPath());
        return Base64.getEncoder().encodeToString(imageBytes);
    }
    public static void main(String[] args) {
        try {
            String base64Image = convertImageToBase64("path/to/your/image.png");
            System.out.println("Base64 Image: " + base64Image);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

包含 MIME 类型的前缀(用于 HTML/CSS)

如果你需要在 HTML 或 CSS 中直接使用 Base64 图片,可以添加 MIME 类型前缀:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
public class ImageToBase64 {
    public static String convertImageToBase64WithPrefix(String imagePath) throws IOException {
        File file = new File(imagePath);
        String mimeType = Files.probeContentType(file.toPath());
        byte[] imageBytes = Files.readAllBytes(file.toPath());
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        return "data:" + mimeType + ";base64," + base64Image;
    }
    public static void main(String[] args) {
        try {
            String base64ImageWithPrefix = convertImageToBase64WithPrefix("path/to/your/image.gif");
            System.out.println("Base64 Image with prefix: " + base64ImageWithPrefix);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意事项

  1. 文件路径:确保提供的图片路径是正确的
  2. 内存使用:对于大图片,使用 Files.readAllBytes() 可能会消耗较多内存
  3. 异常处理:在实际应用中,应该妥善处理可能抛出的异常
  4. 性能:对于大文件,考虑使用缓冲流以提高性能

反向操作(Base64 转图片)

如果你需要将 Base64 字符串转换回图片文件:

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
public class Base64ToImage {
    public static void convertBase64ToImage(String base64Image, String outputPath) throws IOException {
        // 去除前缀(如果有)
        String base64Data = base64Image.split(",")[1];
        byte[] imageBytes = Base64.getDecoder().decode(base64Data);
        try (FileOutputStream imageOutFile = new FileOutputStream(outputPath)) {
            imageOutFile.write(imageBytes);
        }
    }
    public static void main(String[] args) {
        try {
            String base64Image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCdABmX/9k="; // 示例 Base64 字符串
            convertBase64ToImage(base64Image, "output.jpg");
            System.out.println("Image converted successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

方法提供了在 Java 中处理图片与 Base64 编码转换的完整解决方案。

Java图片转Base64,如何实现?-图2
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇