JAVA base64与图片的转换

孤街浪徒 提交于 2020-01-18 01:38:16

想看原文请移步下面
转载:https://www.jianshu.com/p/f9e04600bbf3

Base64生成图片的方法

/**
     * base64生成图片方法
     * @param imgData base64字符串
     * @param imgFilePath 图片的生成路径
     * @return 是否生成成功
     * @throws IOException
     */
    public static String GenerateImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
        if (imgData == null) // 图像数据为空
            return "";
        //随机生成一个UUID并去除他的 "-"
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        imgFilePath += s+".jpg";
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            out = new FileOutputStream(imgFilePath);
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgData);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据


                    b[i] += 256;
                }
            }
            out.write(b);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
            return imgFilePath;
        }
    }

图片生成Base64的方法

/**
     * 图片生成base64方法
     * @param imgPath 图片路径
     * @return
     */
    public static String GetImageStr(String imgPath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        String imgFile = imgPath;// 待处理的图片
        InputStream in = null;
        byte[] data = null;
        String encode = null; // 返回Base64编码过的字节数组字符串
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            // 读取图片字节数组
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            encode = encoder.encode(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return encode;
    }

重要的两个类: BASE64Decoder(解码), BASE64Encoder(编码)

注意: 生成的base64中有多余的 "data:image/jpg;base64,"的前缀, 需要去掉

Controller中的参数 HttpServletRequest request

 //得到路径
 String path = request.getServletContext().getRealPath("WEB-INF/UUID.jpg");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!