zoukankan      html  css  js  c++  java
  • java 图片处理 base64编码和图片二进制编码相互转换-转载

      今天在弄小程序项目时,涉及上传图片的更改。

      以下是代码:

     1 /**
     2      *  -> base64
     3      * @param imgFile
     4      * @return
     5      * @throws IOException
     6      */
     7     public static String getImageStr(String imgFile) throws IOException {
     8         InputStream inputStream = null;
     9         byte[] data = null;
    10         
    11         inputStream = new FileInputStream(imgFile);
    12         data = new byte[inputStream.available()];
    13         inputStream.read(data);
    14         inputStream.close();
    15         
    16         // 加密
    17         BASE64Encoder encoder = new BASE64Encoder();
    18         return encoder.encode(data);
    19     }
     1 /**
     2      * base64 -> 
     3      * @param imgStr
     4      * @param path
     5      * @return
     6      * @throws IOException
     7      */
     8     public static boolean generateImage(String imgStr, String path) throws IOException {
     9         if (imgStr == null){
    10             return false;
    11         }
    12         BASE64Decoder decoder = new BASE64Decoder();
    13         
    14         //解密
    15         byte[] b = decoder.decodeBuffer(imgStr);
    16         // 处理数据
    17         for (int i = 0; i < b.length; ++i) {
    18             if (b[i] < 0) {
    19             b[i] += 256;
    20             }
    21         }
    22         OutputStream out = new FileOutputStream(path);
    23         out.write(b);
    24         out.flush();
    25         out.close();
    26         return true;
    27     }
     1 public static void main(String[] args) throws IOException {
     2         //图片 -》 base64
     3         String imgFile = "F:/Desktop/tupain/kaoshiwancheng.jpg";
     4         getImageStr(imgFile);
     5         
     6         //base64 -> 图片
     7         String imgStr = "imgStr";
     8         String path = "F:/Desktop/tupain/kaoshiwancheng.jpg";
     9         generateImage(imgStr, path);
    10         
    11         
    12     }

      不过需要注意的是,一般插件返回的base64编码的字符串都是有一个前缀的。"data:image/jpeg;base64," 解码之前这个得去掉。

      引用:https://www.cnblogs.com/libra0920/p/5754356.html

  • 相关阅读:
    HTML 5 视频/音频
    vue 未完待续
    asp.net中使用log4net
    图片预加载:jquery 图片预加载功能,可以实现先模糊在清晰的显示
    IIS配置PHP环境
    学习ASP.Net的过滤器
    最好用的jQuery插件,240多个,绝对的JQUERY插件库
    Windows7&IIS7.5部署Discuz全攻略
    AjaxPro使用
    ASP.NET XML读取、增加、修改和删除操作
  • 原文地址:https://www.cnblogs.com/fateSpace/p/10454841.html
Copyright © 2011-2022 走看看