要将图片转换为 Base64 并带有 "data:image/png;base64," 前缀,可以使用 Java 的 Base64 编码器来实现。以下是一个示例代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class ImageToBase64 {
    public static void main(String[] args) {
        String imagePath = \"path/to/your/image.png\";
        String base64Image = convertImageToBase64(imagePath);
        System.out.println(base64Image);
    }

    public static String convertImageToBase64(String imagePath) {
        File file = new File(imagePath);
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            byte[] imageData = new byte[(int) file.length()];
            imageInFile.read(imageData);

            String base64Image = Base64.getEncoder().encodeToString(imageData);
            return \"data:image/png;base64,\" + base64Image;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

请将 imagePath 变量替换为您自己的图片路径。运行上述代码将输出带有 "data:image/png;base64," 前缀的 Base64 编码字符串。

Java 图片转 Base64 编码并添加前缀 (data:image/png;base64,)

原文地址: https://www.cveoy.top/t/topic/pJFS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录