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

转载于:https://www.cnblogs.com/fateSpace/p/10454841.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值