########MD5編碼##############
public static String genMd5ByBytes(byte[] bytes) throws Exception { String value = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(bytes); byte b[] = md5.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } value = buf.toString(); } catch (Exception e) { e.printStackTrace(); throw new Exception("文件進行MD5摘要時出現異常。", e); } return value; }
##########Base64轉為圖片##########
public static String GetImageStr(String imgFilePath) {// 將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理 byte[] data = null; // 讀取圖片字節數組 try { InputStream in = new FileInputStream(imgFilePath); 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編碼過的字節數組字符串 } public static boolean GenerateImage(String imgStr, String imgFilePath) {// 對字節數組字符串進行Base64解碼並生成圖片 if (imgStr == null) // 圖像數據為空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解碼 byte[] bytes = decoder.decodeBuffer(imgStr); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 調整異常數據 bytes[i] += 256; } } // 生成jpeg圖片 OutputStream out = new FileOutputStream(imgFilePath); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } }
使用方法:
public static void main(String[] args) { // 測試從Base64編碼轉換為圖片文件 String strImge = ""; GenerateImage(strImge, "D:\\11.jpg"); // 測試從圖片文件轉換為Base64編碼 // System.out.println(GetImageStr("d:\\11.jpg")); }
