zoukankan      html  css  js  c++  java
  • java实现图片文件与Base64的互转

    通过form表单上传图片时,有时候web容器对文件大小的限制会影响我们上传。这时,前端页面可以考虑将图片转换成base64串来实现上传。

    图片与Base64的互转,其实就是利用了文件流与Base64的互转。

    文件转换成Base64字符串:读取文件的输入流,因为文件流是字节流,所以要放到byte数组(字节数组,byte取值范围-128~127)里,然后对byte数组做Base64编码,返回字符串。

    Base64串转换成文件:对Base64编码的字符串进行Base64解码,得到byte数组,利用文件输出流将byte数据写入到文件。

    Talk is cheap, show me the code。直接上代码:

    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    import java.io.*;
    
    public class ImageBase64Converter {
        /**
         * 本地文件(图片、excel等)转换成Base64字符串
         *
         * @param imgPath     
         */
        public static String convertFileToBase64(String imgPath) {
            byte[] data = null;
            // 读取图片字节数组
            try {
                InputStream in = new FileInputStream(imgPath);
                System.out.println("文件大小(字节)="+in.available());
                data = new byte[in.available()];
                in.read(data);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 对字节数组进行Base64编码,得到Base64编码的字符串
            BASE64Encoder encoder = new BASE64Encoder();
            String base64Str = encoder.encode(data);
            return base64Str;
        }
    
        /**
         * 将base64字符串,生成文件
         */
        public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
    
            BufferedOutputStream bos = null;
            FileOutputStream fos = null;
            File file = null;
            try {
                File dir = new File(filePath);
                if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                    dir.mkdirs();
                }
    
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] bfile = decoder.decodeBuffer(fileBase64String);
    
                file = new File(filePath + File.separator + fileName);
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                bos.write(bfile);
                return file;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    
    }

    test:

    public static void main(String[] args) {
            long start = System.currentTimeMillis();
            String imgBase64Str= ImageBase64Converter.convertFileToBase64("D:\Pictures\科技\liziqi-李子柒爆红.jpg");
    //        System.out.println("本地图片转换Base64:" + imgBase64Str);
            System.out.println("Base64字符串length="+imgBase64Str.length());
            ImageBase64Converter.convertBase64ToFile(imgBase64Str,"D:\Pictures\科技","test.jpg");
            System.out.println("duration:"+(System.currentTimeMillis()-start));
    
            start=System.currentTimeMillis();
            String fileBase64Str= ImageBase64Converter.convertFileToBase64("D:\Pictures\科技\PayOrderList200109075516581.xlsx");
    //        System.out.println("本地excel转换Base64:" + fileBase64Str);
            System.out.println("size="+fileBase64Str.length());
            ImageBase64Converter.convertBase64ToFile(fileBase64Str,"D:\Pictures\科技","test.xlsx");
            System.out.println("duration:"+(System.currentTimeMillis()-start));
    
        }

    执行结果:

    文件大小(字节)=2820811
    Base64字符串length=3860058
    duration:244
    文件大小(字节)=25506
    size=34902
    duration:10

    提醒一下:获取文件的大小是用FileInputStream实例的available()方法哦,用File实例的length()返回的是0。

    如下图,测试方法里图片文件“liziqi-李子柒爆红.jpg”的大小正是2820811字节   ÷1024=2755KB  ÷1024=2.68M

  • 相关阅读:
    Github 简明教程--GitHub这么火,测试员你不学学吗?
    IT行业,尤其是软件测试,怎么才能月薪突破2万?
    linux 下cmake 编译 ,调用,调试 poco 1.6.0 小记
    ffmpeg(2.6) rockplayer android 下编译 小记.
    完成端口
    C++四种强制转换
    方法区(Method Area)基础知识
    逃逸分析
    堆空间参数设置小结
    堆中的线程私有缓存区域TLAB(Thread Local Allocation Buffer)
  • 原文地址:https://www.cnblogs.com/buguge/p/12177895.html
Copyright © 2011-2022 走看看