Android将图库文件夹中的图像复制到SD卡替代文件夹中

Beg*_*ner 3 android copy image sd-card

我正在寻找有人协助我在我的应用程序中需要的代码来复制图像,从而将它们作为标准(图库)存储在HTC欲望的SD卡上的另一个文件夹中.我希望用户能够点击按钮,某个文件从SD卡库文件夹复制到SD卡上的另一个文件夹?谢谢

Wil*_*ate 25

Usmaan,

您可以使用以下命令启动图库选取器意图:

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

返回时,使用以下代码部分获取所选图像的路径:

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);
}
Run Code Online (Sandbox Code Playgroud)

现在您在字符串中有路径名,您可以将其复制到另一个位置.

干杯!

编辑:如果你只需要复制一个文件尝试像...

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) {}
Run Code Online (Sandbox Code Playgroud)