【问题标题】:Android image didn't display to ImageView from image URLAndroid 图像未从图像 URL 显示到 ImageView
【发布时间】:2015-09-23 07:31:36
【问题描述】:

我想将图像从“http://i.imgur.com/4GLKF4Q.jpg”显示到 ImageView,但图像 URL 中的图像没有显示到 imageview。我可以这样做吗?

异步任务

class DownloadImageTask extends AsyncTask<String, Void, byte[]> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected byte[] doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            InputStream is = (InputStream) url.getContent();
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            while ((bytesRead = is.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            return output.toByteArray();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void onPostExecute(byte[] result) {
        ByteArrayInputStream imageStream = new ByteArrayInputStream(result);
        Bitmap bm = BitmapFactory.decodeStream(imageStream);
        bmImage.setImageBitmap(bm);
    }
}

活动中

new DownloadImageTask((ImageView) newView.findViewById(R.id.thumbnail))
            .execute("http://i.imgur.com/4GLKF4Q.jpg");

图片 URL 中的图片没有显示到 imageview。 在 Logcat 中:

09-23 10:26:49.410 10591-10591/com.*** D/skia: --- SkImageDecoder::Factory returned null

【问题讨论】:

标签: java android url imageview


【解决方案1】:

评论更新:将图像服务器更改为另一个解决了问题。我猜这是 i.imgur.com 问题。


您不应该使用自己的图像加载器任务,它会在某处泄漏。 存在两个好的库: - Fresco(来自 Facebook) - Picasso(从 Square 向上)

还有 UniversalImageLoader (UIL)。

【讨论】:

  • 我用毕加索,结果是一样的。 Logcat 日志为 D/skia: --- SkImageDecoder::Factory 返回 null 。当我使用不同的图像 URL 时,它起作用了。 i.imgur.com - 服务器不工作。
  • 嗯,我想可能有人认为这张图片很糟糕,试试 Fresco 看看是否也会发生这种情况。如果是,则可能是您设备上的软件问题
  • 我使用了 fresco 和 SimpleDraweeView 。 Logcat 日志是 --- 原因:java.lang.NullPointerException: SimpleDraweeView 未初始化!
  • as @TahaKörkem 如果认为图像、服务器或设备上的软件解码器有问题。
  • 我使用不同的图像服务器,它的工作。感谢 cmets
【解决方案2】:
  1. 我建议您查看 Facebook 的图像管理库,它是 Fresco,与其他图像加载库相比,它非常棒且成熟。

  2. Fresco 使用 3 层架构(BITMAP_MEMORY_CACHEENCODED_MEMORY_CACHEDISK_CACHE)处理所有图像缓存。它还减少了 OOM(内存不足)问题。当视图中的图像离开屏幕时,它会自动回收位图,从而释放内存。

【讨论】:

    【解决方案3】:

    现在有一个official way 从 URL 加载 ImageView,而不是使用 ImageView。

    NetworkImageView——构建在 ImageLoader 之上,并在通过 URL 通过网络获取图像的情况下有效地替换了 ImageView。如果视图与层次结构分离,NetworkImageView 还管理取消挂起的请求。

    图像在后台线程中自动加载,视图在 UI 线程中更新。它甚至支持缓存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多