Android download and save image through Picasso
1. Make sure you have picasso in your gradle build file’s dependencies tag.
compile 'com.squareup.picasso:picasso:2.5.2'
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.
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
Picasso.with(this).load(anImageUrl).into(picassoImageTarget(getApplicationContext(), "imageDir", "my_image.jpeg"));
4. To load the image after it’s downloaded.
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.
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!");
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts