从Android相册文件夹复制图像到SD卡备用文件夹的替代方法

4

我正在寻找一位助手协助我编写应用程序所需的代码,将存储在HTC Desire标准位置(图库)的图像复制到SD卡上的另一个文件夹。 我希望用户能够点击一个按钮,从SD卡图库文件夹中复制特定文件到SD卡上的另一个文件夹中。谢谢。

2个回答

27

Usmaan,

你可以使用以下方法启动图库选择器意图:

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

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

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);
}

既然你已经将文件路径名存储到字符串中,那么你就可以将其复制到其他位置了。

干杯!

编辑:如果你只需要复制一个文件,可以尝试类似以下的方法...

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) {}

此代码的第一部分将启动您的相册,让您选择一张图片。一旦您选择了图片,它将调用我发布的代码的第二部分中的“onActivityResult()”。它将获取从相册应用返回的数据,而我发布的“getPath()”函数将作为字符串返回所选图像的完整路径。这段代码不允许您使用相机拍照。 - Will Tate
我想把图片复制到另一个文件夹里。并且我不想打开相册,因为我已经知道图片的名字,并且我知道它存储在SD卡的sdcard/dcim/imagename位置上。 - Beginner
寻找类似于将sdcard/dcim/image.jpg复制到sdcard/newfolder的东西。 - Beginner
哦...你只需要实际的副本吗?哈哈,抱歉我之前发布了所有的前置内容,对不起 >< - Will Tate
我只想让用户点击一个按钮,将SD卡/DCIM文件夹中的图像复制到SD卡上的新文件夹中。 - Beginner
显示剩余5条评论

1

Android手机中的图库图片已经存储在SD卡中。官方文档有一个很好的与外部存储器一起工作的章节,你应该去查看一下。


抱歉,我本意是说将图像从那个文件夹复制到另一个文件夹。 - Beginner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接