首页 > 其他 > 详细

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

时间:2021-04-06 23:34:34      阅读:36      评论:0      收藏:0      [点我收藏+]

使用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();
            }
        }
    }

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

原文:https://www.cnblogs.com/xzh-hash/p/14623830.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!