图片 与 base64的相互转化

一、图片 转化成 base64 字符串

  a、本地图片转 base64

   /**
     * @description 将一个本地图片路径转化成Base64字符串
     * @author tank
     * @date 2019/6/12 11:47
     *
     * @param imgFile
     * @return java.lang.String
     */
    public String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

 

  b、网络图片转 base64

   /**   
     * 将网络图片路径转化成base64
     * @param netImagePath   
     */
    private String NetImageToBase64(String netImagePath) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL           
            URL url = new URL(netImagePath);
            byte[] by = new byte[1024];
            // 创建链接           
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中           
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流           
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码       
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }

 

二、base64 转图片

      /**
        * @description 对字节数组字符串进行Base64解码并生成图片
        * @author tank
        * @date 2019/8/19 14:36
        */
    public static boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null){
            // 图像数据为空
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

 

posted @ 2019-08-19 14:37  tank073  阅读(261)  评论(0)    收藏  举报