【问题标题】:Android display image from URL来自 URL 的 Android 显示图像
【发布时间】:2011-09-23 07:18:06
【问题描述】:

如何从下面的 url 加载图像。 http://images.google.com/hosted/life/l?imgurl=46d75bbfa52a8450

我使用 Google 自定义搜索 API 从站点 images.google.com 搜索图像。 它将返回一个带有链接标签内容的 json 文件。示例:http://images.google.com/hosted/life/l?imgurl=46d75bbfa52a8450。我想将它加载到我的视图中。

如果 URL 以文件扩展“.jpg 或 .png”结尾,我可以下载并显示它。 但如果没有,我可以得到图像。 任何人都可以帮助我。

【问题讨论】:

  • 您是否尝试将图像加载到 ImageView 中?你能发布 JSON 响应的内容吗?

标签: android image url


【解决方案1】:

嗨,请使用下面的代码。

  String url = "http://images.google.com/hosted/life/l?imgurl=46d75bbfa52a8450";
    InputStream ins = null;
    try {
        ins = new java.net.URL(url).openStream();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap b = BitmapFactory.decodeStream(new FlushedInputStream(ins));
    imageview.setImageBitmap(b);

 static class FlushedInputStream extends FilterInputStream {
    public FlushedInputStream(InputStream inputStream) {
        super(inputStream);
    }

    @Override
    public long skip(long n) throws IOException {
        long totalBytesSkipped = 0L;
        while (totalBytesSkipped < n) {
            long bytesSkipped = in.skip(n - totalBytesSkipped);
            if (bytesSkipped == 0L) {
                int b = read();
                if (b < 0) {
                    break; // we reached EOF
                } else {
                    bytesSkipped = 1; // we read one byte
                }
            }
            totalBytesSkipped += bytesSkipped;
        }
        return totalBytesSkipped;
    }
  }

【讨论】:

  • 谢谢你给我这个代码。但是当我运行它时。它抛出一个错误 SkImageDecoder::Factory 返回 null。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2017-03-27
  • 2017-01-07
相关资源
最近更新 更多