java 圖片與base64相互轉化的示例
需要導入:
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.UUID;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;
/** * 圖片轉base64字符串 * @param path * @return */public static String PictoBase64(String path) { InputStream in = null; byte[] data = null; // 讀取圖片字節數組 try { in = new FileInputStream(path); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 對字節數組Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);// 返回Base64編碼過的字節數組字符串}/** * base64寫圖片 * @param imgStr * @return */public static boolean Base64toPic(String imgStr) { // 對字節數組字符串進行Base64解碼并生成圖片 if (imgStr == null) // 圖像數據為空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解碼 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 調整異常數據b[i] += 256; } } String imgName = UUID.randomUUID().toString().replace('-', ''); String imgType = '.png'; // 生成png圖片 String imgFilePath = 'C:/Users/Administrator/Desktop/' + imgName + imgType;// 新生成的圖片 OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; }}
以上就是java 圖片與base64相互轉化的示例的詳細內容,更多關于java 圖片與base64相互轉化的資料請關注好吧啦網其它相關文章!
相關文章:
1. ThinkPHP5 通過ajax插入圖片并實時顯示(完整代碼)2. javascript設計模式 ? 建造者模式原理與應用實例分析3. Python使用oslo.vmware管理ESXI虛擬機的示例參考4. IDEA EasyCode 一鍵幫你生成所需代碼5. Java構建JDBC應用程序的實例操作6. 一篇文章帶你了解JavaScript-對象7. IntelliJ IDEA設置條件斷點的方法步驟8. Express 框架中使用 EJS 模板引擎并結合 silly-datetime 庫進行日期格式化的實現方法9. python flask框架快速入門10. 解決Python paramiko 模塊遠程執行ssh 命令 nohup 不生效的問題
