Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save picture to storage using Glide

I'm trying to add a Download feature to my app, I'm using Glide Library to load the pictures from their URL, with the code below, I can save the picture to the device storage, but it's not working as I expected.

                    new AsyncTask<FutureTarget<Bitmap>, Void, Bitmap>() {                         @Override protected Bitmap doInBackground(FutureTarget<Bitmap>... params) {                             try {                                 return params[0].get();                             } catch (Exception ex) {                                 return null;                             }                         }                         @Override protected void onPostExecute(Bitmap bitmap) {                             if(bitmap == null) return;                             MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Art_"+System.currentTimeMillis());                         }                     }.execute(Glide.with(getApplicationContext()).load(url).asBitmap().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(width, height)); 

can anyone help me to get resolve this issue?

like image 526
Mouaad Abdelghafour AITALI Avatar asked Jun 26 '17 14:06

Mouaad Abdelghafour AITALI


People also ask

Where does glide save images?

Google creates a separate link for each image which can be copied-and-pasted into your Glide app spreadsheet. The image picker is pretty basic. Images are stored in Firebase and limited to 10mb files.

How do you download pictures from Glide?

load("YOUR_URL") . asBitmap() . into(new SimpleTarget<Bitmap>(100,100) { @Override public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) { saveImage(resource); } }); Save the bitmap into your memory.


2 Answers

Update

1.Permissions in manifest file

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
  1. Need Coroutine to do some background work
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' 
  1. Glide to get the image as a bitmap
CoroutineScope(Dispatchers.IO).launch {     saveImage(Glide.with(this@MainActivity)         .asBitmap()         .load("https://i.imgur.com/4HFRb2z.jpg") // sample image         .placeholder(android.R.drawable.progress_indeterminate_horizontal) // need placeholder to avoid issue like glide annotations         .error(android.R.drawable.stat_notify_error) // need error to avoid issue like glide annotations         .submit()         .get()) } 
  1. Save the image in a newly created folder with the specific name
private fun saveImage(image: Bitmap): String? {         var savedImagePath: String? = null         val imageFileName = "JPEG_" + "FILE_NAME" + ".jpg"         val storageDir = File(             Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)                 .toString() + "/YOUR_FOLDER_NAME"         )         var success = true         if (!storageDir.exists()) {             success = storageDir.mkdirs()         }         if (success) {             val imageFile = File(storageDir, imageFileName)             savedImagePath = imageFile.getAbsolutePath()             try {                 val fOut: OutputStream = FileOutputStream(imageFile)                 image.compress(Bitmap.CompressFormat.JPEG, 100, fOut)                 fOut.close()             } catch (e: Exception) {                 e.printStackTrace()             }              // Add the image to the system gallery             galleryAddPic(savedImagePath)             //Toast.makeText(this, "IMAGE SAVED", Toast.LENGTH_LONG).show() // to make this working, need to manage coroutine, as this execution is something off the main thread         }         return savedImagePath     } 
  1. Add the image to the gallery and do send broadcast (not mentioning much about as it's out of the question)
 private fun galleryAddPic(imagePath: String?) {         imagePath?.let { path ->             val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)             val f = File(path)             val contentUri: Uri = Uri.fromFile(f)             mediaScanIntent.data = contentUri             sendBroadcast(mediaScanIntent)            }     } 

Original

1.Permissions in manifest file

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

2.Glide to download the image as a bitmap

Glide.with(mContext)          .load("YOUR_URL")          .asBitmap()          .into(new SimpleTarget<Bitmap>(100,100) {              @Override              public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation)  {                    saveImage(resource);              }          }); 
  1. Save the bitmap into your memory
    private String saveImage(Bitmap image) {         String savedImagePath = null;                  String imageFileName = "JPEG_" + "FILE_NAME" + ".jpg";         File storageDir = new File(            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)                            + "/YOUR_FOLDER_NAME");         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);             Toast.makeText(mContext, "IMAGE SAVED", Toast.LENGTH_LONG).show();         }         return savedImagePath;     }         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);         sendBroadcast(mediaScanIntent);     } 
like image 81
Akshay Nandwana Avatar answered Sep 24 '22 14:09

Akshay Nandwana


Basing on Akshay Nandwana answer I used that code to write to internal memory:

Glide.with(context)      .asBitmap()      .load(url)      .into(new SimpleTarget<Bitmap>() {          @Override          public void onResourceReady(Bitmap resource,Transition<? super Bitmap> transition) {             write(fileName, resource);          }      }); 

And here is the write method:

public void write(String fileName, Bitmap bitmap) {     FileOutputStream outputStream;     try {         outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);         outputStream.close();     } catch (Exception error) {         error.printStackTrace();     } } 
like image 23
Wojtek Avatar answered Sep 23 '22 14:09

Wojtek