Fork me on Gitee

Java 处理图片 base64 编码的相互转换

前言:

环境:使用这个代码前:请确保你的JDk是JAVA8及其以上 

 开发测试地址:http://imgbase64.duoshitong.com/   可以查看是否执行成功

 

注意事项:

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

 

Code:

MainTest

 1 /**
 2      * 示例
 3      * @throws UnsupportedEncodingException 
 4      * @throws FileNotFoundException 
 5      */
 6     @SuppressWarnings("resource")
 7     public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {
 8         String strImg = getImageStr("Z:\\水印\\2.bmp");
 9         System.out.println(strImg);
10         File file = new File("z://1.txt");
11         FileOutputStream fos = new FileOutputStream(file);
12         OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
13         try {
14             osw.write(strImg);
15         } catch (IOException e) {
16             // TODO Auto-generated catch block
17             e.printStackTrace();
18         }
19         //generateImage(strImg, "Z:\\水印\\444.bmp");
20         
21     }

加密:

 1 **
 2      * @Description: 根据图片地址转换为base64编码字符串
 3      * @Author:
 4      * @CreateTime:
 5      * @return
 6      */
 7     public static String getImageStr(String imgFile) {
 8         InputStream inputStream = null;
 9         byte[] data = null;
10         try {
11             inputStream = new FileInputStream(imgFile);
12             data = new byte[inputStream.available()];
13             inputStream.read(data);
14             inputStream.close();
15         } catch (IOException e) {
16             e.printStackTrace();
17         }
18         // 加密
19         Encoder encoder = Base64.getEncoder();
20         return encoder.encodeToString(data);
21     }

解密:

 1 /**
 2      * @Description: 将base64编码字符串转换为图片
 3      * @Author: 
 4      * @CreateTime: 
 5      * @param imgStr base64编码字符串
 6      * @param path 图片路径-具体到文件
 7      * @return
 8     */
 9     public static boolean generateImage(String imgStr, String path) {
10             if (imgStr == null)
11                 return false;
12             // 解密
13             try {
14                 Decoder decoder = Base64.getDecoder();
15                 byte[] b = decoder.decode(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             } catch (IOException e) {
28                 return false;
29             }
30     }

 

posted @ 2018-07-22 13:26  ---dgw博客  阅读(6493)  评论(0编辑  收藏  举报