How to save image to SD card on click android button

I use Imageview and a button in 1 XML, and I return the images as a URL from the web server and display them on the ImageView. Now, if the (Save) button is clicked, I need to save this particular image to the SD card. How to do it?

NOTE: This image must be saved.

+8
android android-layout android-widget
source share
2 answers

First, you need to get a bitmap. You can already use it as a Bitmap object, or you can try to get it from ImageView, for example:

BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable(); Bitmap bitmap = drawable.getBitmap(); 

Then you should go to the directory (a File object) from the SD card, for example:

  File sdCardDirectory = Environment.getExternalStorageDirectory(); 

Then create your image storage file:

  File image = new File(sdCardDirectory, "test.png"); 

After that, you just need to write Bitmap thanks to its compress method, for example:

  boolean success = false; // Encode the file as a PNG image. FileOutputStream outStream; try { outStream = new FileOutputStream(image); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); /* 100 to keep full quality of the image */ outStream.flush(); outStream.close(); success = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

Finally, if necessary, process the logical result. For example:

  if (success) { Toast.makeText(getApplicationContext(), "Image saved with success", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Error during image saving", Toast.LENGTH_LONG).show(); } 

Remember to add the following permission to your manifest:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
+49
source share

Probable Solution

Android - Save downloaded image from URL to SD card

 Bitmap bitMapImg; void saveImage() { File filename; try { String path = Environment.getExternalStorageDirectory().toString(); new File(path + "/folder/subfolder").mkdirs(); filename = new File(path + "/folder/subfolder/image.jpg"); FileOutputStream out = new FileOutputStream(filename); bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(), filename.getName(), filename.getName()); Toast.makeText(getApplicationContext(), "File is Saved in " + filename, 1000).show(); } catch (Exception e) { e.printStackTrace(); } } 
+5
source share

All Articles