将图像从 URL 加载到 imageView 以及缓存

Load image from URL to imageView as well as Cache

嗨,我是 android 的新手。我想从 URL 将图像插入到 imageView 中,但是每当它从 URL 加载到 imageView 中时,第二次它应该在没有互联网的情况下插入意味着它也会存储在缓存中。

您可以使用 Picasso 库。

使用Picasso,优点是

  • 在适配器中处理 ImageView 回收 和下载取消。
  • 使用最少的内存进行复杂的图像转换。
  • 自动内存和磁盘缓存

Url

加载 Image
Picasso.with(context).load(url).into(imageView);

为 Api 参考这个 link : Picasso

为此你可以使用毕加索图书馆 您可以从 Picasso Library 站点下载它,只需将此 jar 文件放入 libs 文件夹即可。它将管理图像的所有 属性。 http://square.github.io/picasso/

String imgURL = "Your URL";
ivmage = (ImageView) findViewById(R.id.imageView1);
Picasso.with(MainActivity.this).load(imgURL).into(ivmage);

我建议毕加索图书馆来做这件事。 here是picasso库的详细文档

例如:

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

或者您可以使用 volley 的 ImageLoader。 here 你可以找到 Volley 图片加载的文档。

例如:

// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
    new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap bitmap) {
            mImageView.setImageBitmap(bitmap);
        }
    }, 0, 0, null,
    new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            mImageView.setImageResource(R.drawable.image_load_error);
        }
    });
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);

如果您正在使用排球。那么你必须手动缓存图像。毕加索默认会缓存图片。

你可以使用 Glide https://github.com/bumptech/glide

Glide.with(this).load("imageURl").into(imageView);