Save images in cache memory so as not to download them again

2

Good morning.

I have a series of images in my Activity , every time I enter this Activity download the images, for what I consider that this "wrong", I was reading about the consumption of resources of the images but I am not very clear, I would appreciate if you help me with an example to have a little clearer this concept.

To download images I'm using Picasso introducir el código aquí :

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

Thank you in advance.

    
asked by devjav 17.01.2017 в 15:46
source

2 answers

3

In the case of using Picasso or Glide you can use a callback detecting the loading of the image in ImageView , when loading the image we can create a file to save:

  Picasso.with(ctx).load("http://mydominio.com/my_imagen.png")
                   .into(getTarget(url));

This would be the method:

//Metodo para salvar el target.
private static Target getTarget(final String url){
    Target target = new Target(){

        @Override
        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
            new Thread(new Runnable() {

                @Override
                public void run() {

                    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + url);
                    try {
                        file.createNewFile();
                        FileOutputStream ostream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
                        ostream.flush();
                        ostream.close();
                    } catch (IOException e) {
                        Log.e("IOException", e.getLocalizedMessage());
                    }
                }
            }).start();

        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };
    return target;
}

You can see this in the response from @FernandoNaiva

link

    
answered by 17.01.2017 в 16:21
1

To save a Bitmap in memory you can do the following:

Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
FileOutputStream fos = null;
getFilesDir().mkdirs("cache"); // crear carpeta para cache si no existe 
try {
    fos = openFileOutput("cache/DvpvklR.png");
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (fos != null) {
            fos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

replace the fixed routes with variables according to your needs.

    
answered by 17.01.2017 в 16:14