以下是 Java 程序,可以读取电脑目录上的图片文件,将其转换为 Base64 字符串:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageToBase64 {

    public static void main(String[] args) {
        // 指定图片文件的路径
        String filePath = 'C:/test/sample.jpg';
        // 将图片文件转换为base64字符串
        String base64String = imageToBase64(filePath);
        // 输出转换后的字符串
        System.out.println(base64String);
    }

    /**
     * 将图片文件转换为base64字符串
     *
     * @param filePath 图片文件路径
     * @return base64字符串
     */
    public static String imageToBase64(String filePath) {
        StringBuilder stringBuilder = new StringBuilder();
        FileInputStream inputStream = null;
        try {
            // 读取图片文件
            File file = new File(filePath);
            inputStream = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            inputStream.read(bytes);

            // 将图片文件转换为base64字符串
            stringBuilder.append('data:image/');
            String fileType = filePath.substring(filePath.lastIndexOf('.') + 1);
            stringBuilder.append(fileType);
            stringBuilder.append(';base64,');
            stringBuilder.append(Base64.getEncoder().encodeToString(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }
}

在 main 方法中,我们指定了图片文件的路径,然后调用 imageToBase64 方法将其转换为 Base64 字符串。在 imageToBase64 方法中,我们首先读取图片文件的字节流,然后将其转换为 Base64 字符串,并在字符串前面加上 'data:image/文件类型;base64,' 的前缀,这是为了在前端页面上正确显示图片。最后返回转换后的字符串。

Java 图片转 Base64 编码:快速实现文件编码与展示

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

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