以下是一个示例代码,用于将图片转换为Base64格式并根据图片格式携带前缀:

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 void main(String[] args) {
        String imagePath = "path_to_image"; // 图片路径
        try {
            String base64Image = convertImageToBase64(imagePath);
            System.out.println(base64Image);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String convertImageToBase64(String imagePath) throws IOException {
        File imageFile = new File(imagePath);
        FileInputStream fileInputStream = new FileInputStream(imageFile);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        fileInputStream.close();
        byteArrayOutputStream.close();

        String base64Image;
        String extension = imagePath.substring(imagePath.lastIndexOf(".") + 1);
        switch (extension.toLowerCase()) {
            case "jpg":
            case "jpeg":
                base64Image = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(imageBytes);
                break;
            case "png":
                base64Image = "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
                break;
            case "gif":
                base64Image = "data:image/gif;base64," + Base64.getEncoder().encodeToString(imageBytes);
                break;
            default:
                throw new IllegalArgumentException("Unsupported image format: " + extension);
        }

        return base64Image;
    }
}

在上述代码中,convertImageToBase64方法将根据图片的文件扩展名确定图片格式,并在Base64字符串前面添加相应的前缀。然后,base64Image将包含完整的Base64字符串,包括前缀

java 图片转b64并且根据图片格式携带Base64格式前缀

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

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