標籤:images boolean ret encoder inpu for otf 環境 stack
前言:
環境:使用這個代碼前:請確保你的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 block17 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 }
Java 處理圖片 base64 編碼的相互轉換