Skip to content

Instantly share code, notes, and snippets.

@anandwana001
Last active July 14, 2020 10:26
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save anandwana001/634f72782d6da87d0b6d20d5c7e74100 to your computer and use it in GitHub Desktop.
Save anandwana001/634f72782d6da87d0b6d20d5c7e74100 to your computer and use it in GitHub Desktop.
Save image from network to external storage using Glide
#Step 1
Glide.with(mContext)
.load(images.get(position).getThumbnail())
.asBitmap()
.into(new SimpleTarget<Bitmap>(100,100) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
saveImage(resource,position);
}
});
#Step 2
private String saveImage(Bitmap image, int position) {
String savedImagePath = null;
String imageFileName = "JPEG_" + images.get(position).getName() + ".jpg";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Comicoid");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
}
return savedImagePath;
}
#Step 3
private void galleryAddPic(String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
@AbuBallan
Copy link

We must use Application Context because the target is independent of the activity lifecycle and avoid anonymous object to avoid garbage collector.

@AadeshDhimanDeveloper
Copy link

not working

@hijoem
Copy link

hijoem commented Sep 23, 2019

Works well for me.
What AbuBallan said is true.
But the application get laggy and I get this when running it.

I/Choreographer: Skipped 296 frames! The application may be doing too much work on its main thread.

Do I need to load this code from AsyncTask or something?

@jeluchu
Copy link

jeluchu commented Mar 4, 2020

getExternalStoragePublicDirectory is deprecated on Android Q

@TaslimOseni
Copy link

As a side note, placing .asBitmap() after .load(...) resulted in an error for me.
This error disappeared when I reversed the order.

Here's a StackOverflow question that addresses the issue I was facing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment