Sunday, February 10, 2013

How to save an image to directory in sdcard and update to gallery

This is a short tutorial on how to save an image to directory in sdcard and then update it into gallery.
In this tutorial, I will get an image from drawable folder, then save it to directory in sdcard and update into gallery.

First create a new project with main.xml as shown below:


    

Open MainActivity.java and add a method as shown below:
private void savePicture(Bitmap bm, String imgName)
 {  
  OutputStream fOut = null;
  String strDirectory = Environment.getExternalStorageDirectory().toString();

  File f = new File(strDirectory, imgName);
  try {
   fOut = new FileOutputStream(f);
   
   /**Compress image**/
   bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
   fOut.flush();
   fOut.close();

   /**Update image to gallery**/
   MediaStore.Images.Media.insertImage(getContentResolver(),
    f.getAbsolutePath(), f.getName(), f.getName());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
After compressing, your image will be saved in mnt/sdcard/ with imgName. You can check it by using DDMS prespective. If you want to change where image saved, you can change strDirectory. It can be change to getExternalStoragePublicDirectory(Environment.<your_type>).toString() or your hard path in sdcard.

And the whole MainActivity.java. I set a listener to Button and call savePicture:
private Button saveBtn;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  saveBtn = (Button)findViewById(R.id.saveBtn);
  
  final Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
   
  saveBtn.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    savePicture(bm, "image_name.jpg");
    Toast.makeText(getApplicationContext(), "Image saved...", Toast.LENGTH_SHORT).show();
   }
  });
 }
 
 private void savePicture(Bitmap bm, String imgName)
 {  
  OutputStream fOut = null;
  String strDirectory = Environment.getExternalStorageDirectory().toString();

  File f = new File(strDirectory, imgName);
  try {
   fOut = new FileOutputStream(f);
   
   /**Compress image**/
   bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
   fOut.flush();
   fOut.close();

   /**Update image to gallery**/
   MediaStore.Images.Media.insertImage(getContentResolver(),
    f.getAbsolutePath(), f.getName(), f.getName());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

Note that, in my project, I added a image named my_image.jpg and I just simply called it as a resource. You can make your own by creating a new Bitmap variable and use it.

We also add WRITE_EXTERNAL_STORAGE permission in Manifest.xml:


Finally, open Gallery and check if it works!

No comments:

Post a Comment