1. Make sure you have picasso in your gradle build file’s dependencies tag.
1 2 |
<span class="pln">compile </span><span class="str">'com.squareup.picasso:picasso:2.5.2' </span> |
2. To use the Picasso for saving image file, you need to define a Target class. This method creates a target object that you can use with Picasso. Target is an interface defined in Picasso’s library. You can define this method in your Activity class or an util class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
private Target picassoImageTarget(Context context, final String imageDir, final String imageName) { Log.d("picassoImageTarget", " picassoImageTarget"); ContextWrapper cw = new ContextWrapper(context); final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir return new Target() { @Override public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) { new Thread(new Runnable() { @Override public void run() { final File myImageFile = new File(directory, imageName); // Create image file FileOutputStream fos = null; try { fos = new FileOutputStream(myImageFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath()); } }).start(); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { if (placeHolderDrawable != null) {} } }; } |
3. Now let’s use Picasso to download the image using the Target defined above. We use imageDir as the image directory, and my_image.jpeg for the image name, the image will be saved to /data/data/com.your.app.package.path/app_imageDir/my_image.png
1 |
Picasso.with(this).load(anImageUrl).into(picassoImageTarget(getApplicationContext(), "imageDir", "my_image.jpeg")); |
4. To load the image after it’s downloaded.
1 2 3 4 |
ContextWrapper cw = new ContextWrapper(getApplicationContext()); File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); File myImageFile = new File(directory, "my_image.jpeg"); Picasso.with(this).load(myImageFile).into(ivImage); |
5. To delete the image from the internal storage.
1 2 3 4 |
ContextWrapper cw = new ContextWrapper(getApplicationContext()); File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); File myImageFile = new File(directory, "my_image.jpeg"); if (myImageFile.delete()) log("image on the disk deleted successfully!"); |