1. 程式人生 > >Base64對圖片進行編碼解碼

Base64對圖片進行編碼解碼

public static String GetImageStr(String imgFile) {
        InputStream in = null;
        byte[] data = null;
        // 讀取圖片位元組陣列
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch
(IOException e) { e.printStackTrace(); } // 對位元組陣列Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64編碼過的位元組陣列字串 return encoder.encode(data); } public static boolean GenerateImage(String base64str, String savepath) { // 對位元組陣列字串進行Base64解碼並生成圖片
if (base64str == null) // 影象資料為空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] b = decoder.decodeBuffer(base64str); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 調整異常資料 b[i] += 256
; } } OutputStream out = new FileOutputStream(savepath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } }