Search code examples
androidfileandroid-gallery

Store an image from gallery to a different folder


So far what i have achieved is that i can store Image clicked from camera to a new folder

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        f = new File(Utils.getPath(), new Date().getTime() + ".jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        startActivityForResult(intent, TAKE_PHOTO);

But I dont know how to store an Image selected from gallery to the same folder i created. Please help me. Thank you in advance.


Solution

  • First, get real path from URI you got from gallery.

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        startManagingCursor(cursor);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    

    now copy image to another location,

     private void copyFile(File sourceFile, File destFile) throws IOException {
                if (!sourceFile.exists()) {
                    return;
                }
    
                FileChannel source = null;
                    FileChannel destination = null;
                    source = new FileInputStream(sourceFile).getChannel();
                    destination = new FileOutputStream(destFile).getChannel();
                    if (destination != null && source != null) {
                        destination.transferFrom(source, 0, source.size());
                    }
                    if (source != null) {
                        source.close();
                    }
                    if (destination != null) {
                        destination.close();
                    }  
        }
    
    
    
      File destFile = new File("Dest path");
    
      copyFile(new File(getPath(data.getData())), destFile);
    

    check out urls for more details,

    1. How to Copy Image File from Gallery to another folder programmatically in Android

    2. Android copy image from gallery folder onto SD Card alternative folder