图片转Base64

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

public class ImageToBase64 {
    /**
     * 本地图片转Base64
     * @param imagePath
     * @return
     */
    public static String imageToBase64(String imagePath) {
        File file = new File(imagePath);
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] imageData = new byte[(int) file.length()];
            fis.read(imageData);
            fis.close();
            String base64Image = Base64.getEncoder().encodeToString(imageData);
            System.out.println("Base64编码的图片: " + base64Image);
            return  base64Image;
        } catch (IOException e) {
            e.printStackTrace();
            return  "转码失败";
        }
    }

    /**
     * 截图文件转Base64
     * @param file
     * @return
     */
    public static String fileImageToBase64(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] imageData = new byte[(int) file.length()];
            fis.read(imageData);
            fis.close();
            String base64Image = Base64.getEncoder().encodeToString(imageData);
            System.out.println("Base64编码的图片: " + base64Image);
            return  base64Image;
        } catch (IOException e) {
            e.printStackTrace();
            return  "转码失败";
        }
    }


    public static void main(String[] args) {
        new ImageToBase64().imageToBase64("src/main/resources/yzm/code.jpg");
        new ImageToBase64().fileImageToBase64(new File("src/main/resources/yzm/code.jpg"));
    }
}

 

posted @ 2023-11-17 10:22  o小兵o  阅读(24)  评论(0编辑  收藏  举报