java遠程擷取圖片產生base64串

來源:互聯網
上載者:User

標籤:springmvc   mysql   mybatis   oracle   sqlserver   

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

Java代碼  650) this.width=650;" class="star" src="http://songfeng-123.iteye.com/images/icon_star.png" alt="收藏代碼" style="border:0px;" />

  1. /** 

  2.  * 遠程讀取image轉換為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. }  


java遠程擷取圖片產生base64串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.