Java處理圖片實現base64編碼轉換
前言
環境:使用這個代碼前:請確保你的JDk是JAVA8及其以上
開發測試地址:http://imgbase64.duoshitong.com/ 可以查看是否執行成功
注意事項
一般插件返回的base64編碼的字符串都是有一個前綴的。'data:image/jpeg;base64,' 解碼之前這個得去掉。
Code
MainTest
/** * 示例 * @throws UnsupportedEncodingException * @throws FileNotFoundException */ @SuppressWarnings('resource') public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException { String strImg = getImageStr('Z:水印2.bmp'); System.out.println(strImg); File file = new File('z://1.txt'); FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, 'UTF-8'); try { osw.write(strImg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //generateImage(strImg, 'Z:水印444.bmp'); }
加密:
** * @Description: 根據圖片地址轉換為base64編碼字符串 * @Author: * @CreateTime: * @return */ public static String getImageStr(String imgFile) { InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(imgFile); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 加密 Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(data); }
解密:
/** * @Description: 將base64編碼字符串轉換為圖片 * @Author: * @CreateTime: * @param imgStr base64編碼字符串 * @param path 圖片路徑-具體到文件 * @return */ public static boolean generateImage(String imgStr, String path) { if (imgStr == null)return false; // 解密 try {Decoder decoder = Base64.getDecoder();byte[] b = decoder.decode(imgStr);// 處理數據for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; }}OutputStream out = new FileOutputStream(path);out.write(b);out.flush();out.close();return true; } catch (IOException e) {return false; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. Spring security 自定義過濾器實現Json參數傳遞并兼容表單參數(實例代碼)2. docker /var/lib/docker/aufs/mnt 目錄清理方法3. JAMon(Java Application Monitor)備忘記4. Python OpenCV去除字母后面的雜線操作5. 在Mac中配置Python虛擬環境過程解析6. IntelliJ IDEA設置默認瀏覽器的方法7. IntelliJ IDEA設置背景圖片的方法步驟8. Python TestSuite生成測試報告過程解析9. Python 的 __str__ 和 __repr__ 方法對比10. Java類加載機制實現步驟解析
