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

  • 相关阅读:
    Android NDK 学习之传递类对象
    https://www.aminer.cn/ AI研究
    MYSQL 的一些文件及说明
    Windows下移动MariaDB数据目录 (转!)
    MariaDB Galera Cluster 10.1 只支持 LINUX ?!
    MARIADB 在 OPENSUSE 的安装。
    “命令行程序”的通用图形界面 (转)
    代码生成的地址:mygeneration
    上海力软--快速开发框架
    康力优蓝机器人 -- 优友U05类人型机器人发布
  • 原文地址:https://www.cnblogs.com/fateSpace/p/10454841.html
Copyright © 2011-2022 走看看