从url转换为位图时,位图返回null

时间:2017-09-14 12:58:50

标签: android bitmap drawable firebase-storage

我知道有很多关于同一问题的问题,我尝试了许多解决方案,如this,但我仍然得到空字符串。 这是我的代码

try {
      URL url = new URL(myUrl);
      InputStream in = url.openConnection().getInputStream();
      BufferedInputStream bis = new BufferedInputStream(in,1024*8);
      ByteArrayOutputStream out = new ByteArrayOutputStream();

      int len=0;
      byte[] buffer = new byte[1024];
      while((len = bis.read(buffer)) != -1) {
            out.write(buffer, 0, len);
      }
      out.close();
      bis.close();

      byte[] data = out.toByteArray();
      Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);

      d = new BitmapDrawable(getResources(), bmp);

} catch (FileNotFoundException e) {
      d = getResources().getDrawable(R.mipmap.background);
} catch (MalformedURLException e) {
      e.printStackTrace();
} catch (IOException e) {
      e.printStackTrace();
}
  

myUrl是firebase存储网址

1 个答案:

答案 0 :(得分:1)

在您的gradle文件中添加Picassso图书馆

compile 'com.squareup.picasso:picasso:2.5.2'

比使用这样的毕加索下载图像:

 Picasso.with(this)
.load(myUrl)
.into(new Target() {
      @Override
      public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { 

              //Convert your drawable here
              d = new BitmapDrawable(getResources(), bitmap);

      }

      @Override
      public void onBitmapFailed(Drawable errorDrawable) {

      }

      @Override
      public void onPrepareLoad(Drawable placeHolderDrawable) {

      }
 });