Java處理圖片實(shí)現(xiàn)base64編碼轉(zhuǎn)換
前言
環(huán)境:使用這個(gè)代碼前:請(qǐng)確保你的JDk是JAVA8及其以上
開發(fā)測(cè)試地址:http://imgbase64.duoshitong.com/ 可以查看是否執(zhí)行成功
注意事項(xiàng)
一般插件返回的base64編碼的字符串都是有一個(gè)前綴的。'data:image/jpeg;base64,' 解碼之前這個(gè)得去掉。
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: 根據(jù)圖片地址轉(zhuǎn)換為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編碼字符串轉(zhuǎn)換為圖片 * @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);// 處理數(shù)據(jù)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; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Java封裝數(shù)組實(shí)現(xiàn)包含、搜索和刪除元素操作詳解2. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式3. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)4. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟5. python基于socket模擬實(shí)現(xiàn)ssh遠(yuǎn)程執(zhí)行命令6. Django-migrate報(bào)錯(cuò)問題解決方案7. JAVA上加密算法的實(shí)現(xiàn)用例8. 使用Python和百度語音識(shí)別生成視頻字幕的實(shí)現(xiàn)9. idea打開多個(gè)窗口的操作方法10. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問題……
