使用Base64编码对图片文件进行转换

使用Base64编码对图片文件进行转换

图片转base64

	@Test
    public void imageToBase64(){
        byte[] data = null;
        FileInputStream in = null;
        PrintWriter printWriter = null;
        try {
            in = new FileInputStream("D:\\image.jpg");
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\11.txt");
            printWriter = new PrintWriter(fileOutputStream);
            data = new byte[in.available()];
            in.read(data);//关键要点
            String str1 = Base64.encodeBase64String(data);//tomcat包
            java.util.Base64.Encoder encoder2 = java.util.Base64.getEncoder();
            String str2 = encoder2.encodeToString(data);
            String str3 = cn.hutool.core.codec.Base64.encode(new File("D:\\image.jpg"));
            System.out.println(str3);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
                printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

图片转base64编码很多工具包都有,java.util,hutool,tomcat,随意选择一个即可

base64编码转图片

public static void base64ToImage(String base64str) {
        String imgPath = "D:\\image.jpg";
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(imgPath);
            java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
            byte[] imageData = decoder.decode(base64str);
            out.write(imageData);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
posted @ 2021-04-06 21:26  xzzzzzzz  阅读(1210)  评论(0)    收藏  举报