Как копировать выбранное изображение в нужную папку? Android

Использую следующий код для выбора изображения:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PHOTO);

Далее, в onActivityResult() мне нужно скопировать полученное изображение в папку. Какими методами я могу это сделать? Перепробовал уже все, что только пришло в голову. Метод FileUtils.copy() применить не получается.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_PHOTO && resultCode == Activity.RESULT_OK) {

            File destination = Environment.getExternalStorageDirectory();
            File source = new File(data.getData().toString());
            try
            {
                FileUtils.copy(source, destination);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

В чем моя ошибка?


Ответы (1 шт):

Автор решения: denisnumb

Нашел решение:

Поменял ACTION_OPEN_DOCUMENT на ACTION_PICK, потому второй вариант работает большем количестве моих устройств. А первый, в некоторых случаях, приходится менять на ACTION_GET_CONTENT

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

1. В onActivityResult, создаем путь "Fdestination", который ведет в корневую папку приложения и задает скопированному файлу имя "sm_background.png". Создаем файл "destination" по пути "Fdestination".

2. Метод getRealPathFromURI(data.getData()) - получаем путь к выбранному изображению и при помощи метода copyFile копируем его в корневую папку.

3. Uri bg = Uri.fromFile(destination); - получаем путь до скопированного изображения в корневой папке.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_PHOTO && resultCode == Activity.RESULT_OK) {
            String Fdestination = getFilesDir()+"/sm_background.png";
            File destination = new File(Fdestination);
            try {
                copyFile(new File(getRealPathFromURI(data.getData())), destination);
            } catch (Exception e) {

            }
            Uri bg = Uri.fromFile(destination);
        }
    }

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


    }

    private String getRealPathFromURI(Uri contentUri) {

        String[] proj = { MediaStore.Video.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
→ Ссылка