獲取網絡圖片

//根據url獲取網絡圖片並轉化爲byte數組,方便操作

public  byte[] getBytesByURL(String imageUrl)throws IOException {
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
       BufferedInputStream bis = null;
       HttpURLConnection urlconnection= null;
       URL url = null;
      //創建一個Buffer字符串
       byte[] buf = new byte[1024];
       try {
           url = new URL(imageUrl);
           urlconnection = (HttpURLConnection) url.openConnection();
           urlconnection.connect();
           bis = new BufferedInputStream(urlconnection.getInputStream());
           for (int len = 0; (len = bis.read(buf)) != -1;){
           bos.write(buf,0,len);
           }
       } finally {
           try {
                urlconnection.disconnect();
                bis.close();
           } catch (IOException ignore) {
           }
       }
       return bos.toByteArray();
  }

//根據url返回bufferedImage

public static BufferedImage RequestImage(String imageurl) throws IOException{
   URL url = new URL(imageurl); 
try {
   InputStream inputStream=url.openStream();
BufferedImage  bufferedImage=ImageIO.read(inputStream);
return bufferedImage;
} catch (IOException e) {
e.printStackTrace();
return null;
}
  }




發佈了30 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章