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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM