利用网络请求将网络图片转换成Bitmap格式

利用网络请求将图片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();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容