Save Image in Folder in Android

In this blog post, I would like to explain how to create an folder inside the gallery folder, and save an image within that folder in Android.

An image can be chosen in following two ways.

  • From Gallery
  • Taken by Camera

Let’s see one by one.

From Gallery
In this way, an image is chosen from Gallery(An existing image from gallery).
Include the following code to choose the image from Gallery.

Intent intent = new Intent(Intent.ACTION_PICK);
        	    intent.setType("image/*");
        	    startActivityForResult(intent, 1);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	    super.onActivityResult(requestCode, resultCode, data);

	    if (resultCode == RESULT_OK) {

                    Uri selectedImage = data.getData();

	            String[] filePath = { MediaStore.Images.Media.DATA };

	            Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);

	            c.moveToFirst();

	            int columnIndex = c.getColumnIndex(filePath[0]);

	            picturePath = c.getString(columnIndex);

	            c.close();

	            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));

                     saveImage(thumbnail);
}
}

	private void saveImage(Bitmap finalBitmap) {
	    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
	    System.out.println(root +" Root value in saveImage Function");
	    File myDir = new File(root + "/folder_name");

	    if (!myDir.exists()) {
	    	myDir.mkdirs();
        }

	    Random generator = new Random();
	    int n = 10000;
	    n = generator.nextInt(n);
	    iname = "Image-" + n + ".jpg";
	    File file = new File(myDir, iname);
	    if (file.exists())
	        file.delete();
	    try {
	        FileOutputStream out = new FileOutputStream(file);
	        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
	        out.flush();
	        out.close();
	    }
	    catch (Exception e) {
	        e.printStackTrace();
	    }

	    // Tell the media scanner about the new file so that it is
	    // immediately available to the user.
	    MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
	            new MediaScannerConnection.OnScanCompletedListener() {
	                public void onScanCompleted(String path, Uri uri) {
	                    Log.i("ExternalStorage", "Scanned " + path + ":");
	                    Log.i("ExternalStorage", "-> uri=" + uri);
	                }
	    });

	    Image_path = Environment.getExternalStorageDirectory()+ "/Pictures/folder_name/"+iname;

	    File[] files = myDir.listFiles();
    	numberOfImages=files.length;
    	System.out.println("Total images in Folder "+numberOfImages);
	}

By Camera

In this way the image is taken by the camera.

Inlude the following code to take image by camera.


Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

     	                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

     	                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

     	                    startActivityForResult(intent, 1);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	    super.onActivityResult(requestCode, resultCode, data);

	    if (resultCode == RESULT_OK) {
 Bitmap bitmap;

	                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

	                picturePath=f.getAbsolutePath();
	                System.out.println(picturePath+" Picture path in side the Onactivity method");

	                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),

	                        bitmapOptions); 

	                MediaStore.Images.Media.insertImage(getContentResolver(),
	                        bitmap,
	                        String.valueOf(System.currentTimeMillis()),
	                        "Description");
                       saveImage(bitmap);

	private void saveImage(Bitmap finalBitmap) {
	    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
	    System.out.println(root +" Root value in saveImage Function");
	    File myDir = new File(root + "/folder_name");

	    if (!myDir.exists()) {
	    	myDir.mkdirs();
        }

	    Random generator = new Random();
	    int n = 10000;
	    n = generator.nextInt(n);
	    iname = "Image-" + n + ".jpg";
	    File file = new File(myDir, iname);
	    if (file.exists())
	        file.delete();
	    try {
	        FileOutputStream out = new FileOutputStream(file);
	        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
	        out.flush();
	        out.close();
	    }
	    catch (Exception e) {
	        e.printStackTrace();
	    }

	    // Tell the media scanner about the new file so that it is
	    // immediately available to the user.
	    MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
	            new MediaScannerConnection.OnScanCompletedListener() {
	                public void onScanCompleted(String path, Uri uri) {
	                    Log.i("ExternalStorage", "Scanned " + path + ":");
	                    Log.i("ExternalStorage", "-> uri=" + uri);
	                }
	    });

	    Image_path = Environment.getExternalStorageDirectory()+ "/Pictures/folder_name/"+iname;

	    File[] files = myDir.listFiles();
    	numberOfImages=files.length;
    	System.out.println("Total images in Folder "+numberOfImages);
	}
}
}

Hope this blog post was helpful. Do let me know your feedback.

Leave a Reply

Your email address will not be published. Required fields are marked *