How do I use disk caching in Picasso?

前端 未结 9 865
-上瘾入骨i
-上瘾入骨i 2020-11-22 14:44

I am using Picasso to display image in my android app:

/**
* load image.This is within a activity so this context is activity
*/
public void loadImage (){
           


        
9条回答
  •  长发绾君心
    2020-11-22 15:40

    I don't know how good that solution is but it is definitely THE EASY ONE i just used in my app and it is working fine

    you load the image like that

    public void loadImage (){
    Picasso picasso = Picasso.get(); 
    picasso.setIndicatorsEnabled(true);
    picasso.load(quiz.getImageUrl()).into(quizImage);
    }
    

    You can get the bimap like that

    Bitmap bitmap = Picasso.get().load(quiz.getImageUrl()).get();
    

    Now covert that Bitmap into a JPG file and store in the in the cache, below is complete code for getting the bimap and caching it

    Thread thread = new Thread() {
     public void run() {
     File file = new File(getCacheDir() + "/" +member.getMemberId() + ".jpg");
    
    try {
          Bitmap bitmap = Picasso.get().load(uri).get();
          FileOutputStream fOut = new FileOutputStream(file);                                        
          bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
    fOut.flush();
    fOut.close();
        }
    catch (Exception e) {
      e.printStackTrace();
        }
       }
    };
         thread.start();
      })
    
    

    the get() method of Piccasso for some reason needed to be called on separate thread , i am saving that image also on that same thread.

    Once the image is saved you can get all the files like that

    List files = new LinkedList<>(Arrays.asList(context.getExternalCacheDir().listFiles()));
    

    now you can find the file you are looking for like below

    for(File file : files){
                    if(file.getName().equals("fileyouarelookingfor" + ".jpg")){ // you need the name of the file, for example you are storing user image and the his image name is same as his id , you can call getId() on user to get the file name
                        Picasso.get() // if file found then load it
                                .load(file)
                                .into(mThumbnailImage);
                        return; // return 
                    }
            // fetch it over the internet here because the file is not found
           }
    

提交回复
热议问题