java遠程獲取圖片生成base64串

說下背景,項目中遇到前端js獲取圖片發生跨域的問題,服務器端又不支持匿名訪問,只能通過服務器獲取圖片base64碼進行展示。代碼如下:下載

Java代碼  收藏代碼

  1. /** 

  2.  * 遠程讀取p_w_picpath轉換爲Base64字符串 

  3.  * @param imgUrl 

  4.  * @return 

  5.  */  

  6. private String Image2Base64(String imgUrl) {  

  7.     URL url = null;  

  8.     InputStream is = null;   

  9.     ByteArrayOutputStream outStream = null;  

  10.     HttpURLConnection httpUrl = null;  

  11.     try{  

  12.         url = new URL(imgUrl);  

  13.         httpUrl = (HttpURLConnection) url.openConnection();  

  14.         httpUrl.connect();  

  15.         httpUrl.getInputStream();  

  16.         is = httpUrl.getInputStream();            

  17.           

  18.         outStream = new ByteArrayOutputStream();  

  19.         //創建一個Buffer字符串  

  20.         byte[] buffer = new byte[1024];  

  21.         //每次讀取的字符串長度,如果爲-1,代表全部讀取完畢  

  22.         int len = 0;  

  23.         //使用一個輸入流從buffer裏把數據讀取出來  

  24.         while( (len=is.read(buffer)) != -1 ){  

  25.             //用輸出流往buffer裏寫入數據,中間參數代表從哪個位置開始讀,len代表讀取的長度  

  26.             outStream.write(buffer, 0, len);  

  27.         }  

  28.         // 對字節數組Base64編碼  

  29.         return new BASE64Encoder().encode(outStream.toByteArray());  

  30.     }catch (Exception e) {  

  31.         e.printStackTrace();  

  32.     }  下載

  33.     finally{  

  34.         if(is != null)  

  35.         {  

  36.             try {  

  37.                 is.close();  

  38.             } catch (IOException e) {  

  39.                 e.printStackTrace();  

  40.             }  

  41.         }  

  42.         if(outStream != null)  

  43.         {  

  44.             try {  

  45.                 outStream.close();  

  46.             } catch (IOException e) {  

  47.                 e.printStackTrace();  

  48.             }  

  49.         }  

  50.         if(httpUrl != null)  

  51.         {  

  52.             httpUrl.disconnect();  

  53.         }  

  54.     }  

  55.     return imgUrl;  

  56. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章