Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android copy image from gallery folder onto SD Card alternative folder

I am looking for someone to assist in the code i require in my application to copya image from where they get stored on the HTC desire as standard(the gallery) to a another folder on the SD card. I want the user to be able to click on a button and a certain file is copied from the SD card gallery folder to the another folder on the SD card? Thanks

like image 249
Beginner Avatar asked Nov 28 '22 18:11

Beginner


2 Answers

Usmaan,

You can launch the gallery picker intent with the following:

    public void imageFromGallery() {
    Intent getImageFromGalleryIntent = 
      new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(getImageFromGalleryIntent, SELECT_IMAGE);
}

When it returns, get the path of the selected image with the following portion of code:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        switch(requestCode) {
        case SELECT_IMAGE:
            mSelectedImagePath = getPath(data.getData());
            break;
    }
}

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 that you have the pathname in a string you can copy it to another location.

Cheers!

EDIT: If you just need to copy a file try something like...

try {
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    if (sd.canWrite()) {
        String sourceImagePath= "/path/to/source/file.jpg";
        String destinationImagePath= "/path/to/destination/file.jpg";
        File source= new File(data, sourceImagePath);
        File destination= new File(sd, destinationImagePath);
        if (source.exists()) {
            FileChannel src = new FileInputStream(source).getChannel();
            FileChannel dst = new FileOutputStream(destination).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
        }
    }
} catch (Exception e) {}
like image 138
Will Tate Avatar answered Nov 30 '22 07:11

Will Tate


Gallery images are already stored in the SD card in Android phones. The official documentation has a nice section on working with external storage, which you should check out.

like image 41
goncalossilva Avatar answered Nov 30 '22 06:11

goncalossilva