为什么BitmapFactory.decodeStream返回null?

问题描述

我想使用this example从url下载图像:

public Bitmap getBitmapFromURL(String src) {
    try {
        java.net.URL url = new java.net.URL(src);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printstacktrace();
        return null;
    }
}

很遗憾,返回的myBitmapnull,我不知道为什么。网址是本地ip:http://192.168.0.101:7777/my_image.png

  • 我没有收到错误消息
  • 如果我在浏览器中打开此链接,它将显示它。
  • android:usesCleartextTraffic="true"已启用,我的json请求可与Volley一起使用。
  • 我尝试使用BufferedInputStream,但这也不起作用

解决方法

如果位图对于可用内存变大,则BimapFactory.decodeStream()返回null。

因此,您正在尝试以高分辨率加载图片。

尝试加载一张小图片,它将消失。

,

这有多简单和酷?使用Glide

      ImageView imageView = findViewById(R.id.imageView);
      Glide.with(this)
           .asBitmap()
           .load("https://www.google.com/images/srpr/logo11w.png")
           .into(new CustomTarget<Bitmap>() {
         @Override
         public void onResourceReady(@NonNull Bitmap resource,@Nullable Transition<? super Bitmap> transition) {
            imageView.setImageBitmap(resource);
         }
         @Override
         public void onLoadCleared(@Nullable Drawable placeholder) {
         }
      });

或者您也可以尝试使用这些选项

public static Bitmap loadImage(String imageUrl) {
        Bitmap bitmap = null;
        try {
                URL url = new URL(imageUrl);
                bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (MalformedURLException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
        return bitmap;
    }

public static Bitmap downloadImage(String urlImage) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            URL url = new URL(urlImage);
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.
                    decodeStream(new FlushedInputStream(stream),null,bmOptions);
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }