base642photo

/**
     * pic to base64Str
     * @param path 讀取路徑
     * @return
     */
    public static String GetImageStr(String path) {//轉化成base64字符串
        String imgFile = path;
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data);// 返回Base64編碼過的字節數組字符串
        } catch (IOException e) {
            logger.error("圖片轉換base64字符串出錯"+e.getMessage());
        }
        return "";
    }
    /**
     *  base64Str to pic
     * @param imgStr base64 字符串
     * @param path 存儲路徑
     * @return
     */
    public static boolean GenerateImage(String imgStr,String path) { // 對字節數組字符串進行Base64解碼並生成
        if (imgStr == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 調整異常數據
                    b[i] += 256;
                }
            }
            File file = new File(path);
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }

            OutputStream out = new FileOutputStream(new File(path));
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }數組

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息