Skip to content

Instantly share code, notes, and snippets.

@AbuBallan
Forked from anandwana001/OnButtonClick.java
Last active August 23, 2019 19:34
Show Gist options
  • Save AbuBallan/7df10e196fcc7f71a86195d8472e347c to your computer and use it in GitHub Desktop.
Save AbuBallan/7df10e196fcc7f71a86195d8472e347c to your computer and use it in GitHub Desktop.
Save image from network to external storage using Glide
// Step 1
private void saveImage(String source) {
SimpleTarget<Bitmap> simpleTarget = new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
saveImage(resource, position);
}
};
Glide
.with(getApplicationContext())
.asBitmap()
.load(source)
.into(simpleTarget);
}
// 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);
getApplicationContext().sendBroadcast(mediaScanIntent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment