利用網路請求將網路圖片轉換成Bitmap格式

weixin_33913332發表於2018-07-17

利用網路請求將圖片url轉化成Bitmap

/**
 * 獲取網路圖片
 *
 * @param imageurl 圖片網路地址
 * @return Bitmap 返回點陣圖
 */
public Vector<Bitmap> GetImageInputStream(List<String> imageurl) {
  Vector<Bitmap> bitmaps = new Vector<>();
  new Thread(new Runnable() {
    @Override public void run() {
      URL url = null;
      HttpURLConnection connection = null;
      Bitmap bitmap = null;
      for (int i = 0; i < imageurl.size(); i++) {
        try {
          url = new URL(imageurl.get(i));
        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
        try {
          connection = (HttpURLConnection) url.openConnection();
          connection.setConnectTimeout(6000); //超時設定
          connection.setDoInput(true);
          connection.setUseCaches(false); //設定不使用快取
          connection.connect();
          InputStream inputStream = connection.getInputStream();
          if (inputStream==null){
            throw  new RuntimeException("stream is null");
          }else {
            try{
              byte[] data=readStream(inputStream);
              if (data!=null){
                bitmap= BitmapFactory.decodeByteArray(data,0,data.length);
              }
            }catch (Exception e){
              e.printStackTrace();
            }
            inputStream.close();
            bitmaps.add(bitmap);
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }).start();
  System.out.println("----------------------------"+bitmaps.size());
  return bitmaps;
}

獲取圖片位元組流

/*
 * 得到圖片位元組流 陣列大小
 * */
public static byte[] readStream(InputStream inStream) throws Exception{
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while( (len=inStream.read(buffer)) != -1){
    outStream.write(buffer, 0, len);
  }
  outStream.close();
  inStream.close();
  return outStream.toByteArray();
}

相關文章