【问题标题】:Android : How to set an image to an imageview from a url programaticallyAndroid:如何以编程方式将图像从 url 设置为 imageview
【发布时间】:2017-10-13 18:51:25
【问题描述】:

我有一个来自我的 rest API 的图像 url。现在我想在加载活动时将其设置为图像视图。下面是我如何从 rest api 获取 bean,然后从中获取 URL。

Message message=new Message();
String imageUrl=message.getImageUrl();

我从我的数据库中获取 Message 对象,并且图像 url 包含在该 Message 对象中。

然后我使用 Url 对象来获取该图像 url。

URL url = null;
try {
     url = new URL(imageUrl);
     Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
     contentImageView.setImageBitmap(bmp);
} catch (Exception e) {
     e.printStackTrace();
}

我使用上面的代码将图像加载到 contentImageView 的 imageview 对象。

但我仍然无法将此图像加载到 imageview,什么都没有加载。

有什么想法吗?

【问题讨论】:

  • 将位图图像更改为某个图片,通过在图像视图中显示图片来查看您是否捕捉到任何异常。
  • 您必须在 AsyncTask 中加载 imageview。从网址完全下载图像后,您可以在 imageview 中显示图像。

标签: android image url bitmap imageview


【解决方案1】:

请尝试此功能获取bitmap

public Bitmap getBitmapfromUrl(String imageUrl)
{
    try
    {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

    } catch (Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;

    }
}

【讨论】:

    【解决方案2】:

    如果你想在没有任何库的情况下这样做:

    1. 如果内存中有位图图像

      setImageBitmap(Bitmap bm) // 设置一个 Bitmap 作为这个 ImageView 的内容。

    2. 如果你在drawable文件夹中有图片

      setImageResource(int resId) // 设置一个drawable作为这个ImageView的内容。

    参考:https://developer.android.com/reference/android/widget/ImageView.html

    【讨论】:

      【解决方案3】:

      最简单的方法是使用 Picasso 或 Glide 之类的东西:

      Picasso.with(getContext()).load(imgUrl).fit().into(contentImageView);
      

      您可以在 gradle 中添加 picasso 库: compile 'com.squareup.picasso:picasso:2.5.2'

      【讨论】:

      • 是的,使用 Picasso 很棒,但是将它与 loopers 和 handlers 一起使用可以非常有效地获取和回收。
      【解决方案4】:

      使用 Glide 或 picasa 库来提高性能

      依赖

      compile 'com.github.bumptech.glide:glide:3.7.0'
      

      示例代码

        Glide.with(this)
                      .load(url)
                      .diskCacheStrategy(DiskCacheStrategy.NONE)
                      .skipMemoryCache(true)
                      .into(imageview);
      

      参考资料: Glide 官方文档https://github.com/bumptech/glide

      【讨论】:

        猜你喜欢
        • 2017-04-27
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 2020-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多