將圖片路徑轉換為圖片的base64格式
阿新 • • 發佈:2018-11-22
// 圖片轉化成base64字串 public static String GetImageStr(String imgFile) throws Exception {// 將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理 InputStream in = null; byte[] data = null; // 讀取圖片位元組陣列 ByteArrayOutputStream outputstream = null; int index = imgFile.lastIndexOf("."); String args1 = "jpg"; if (index > -1 && index < (imgFile.length() - 1)) { args1 = imgFile.substring(index + 1); } else { throw new Exception("檔案字尾有誤url=" + imgFile); } URL url = new URL(imgFile); BufferedImage bufferedImage=null; try { bufferedImage = ImageIO.read(url); } catch (Exception e) { throw new Exception("讀取圖片url["+imgFile+"]有誤!"); } // 開始對圖片進行壓縮 outputstream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, args1, outputstream); double k = outputstream.size(); int count = 0; double com = 100 * 1024 * 0.9;// 比對基礎大小 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(outputstream.toByteArray()); }