Pick up an Image from the gallery and move to a folder

0

I am using the following code to get the path of an image from the system:

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

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){

        Uri imagemSelecionada = intent.getData();

}

And it seems to be working fine, but my goal is to get the path of the image and move to the "/app/imagens/" folder that is in the internal memory.

I researched a lot on the web but found no practical solution to my problem.

I found the following code on the web and it works fine for static path:

File sd=Environment.getExternalStorageDirectory();
String sourcePath="/.Images/";
File file = new File(sd,sourcePath);
boolean success = file.renameTo(new File(sd, "nome qualquer"));}

However, the image path varies with each request.

I've read several posts of Google's own and I have not reached any conclusion, I was looking at the stack overflow.

I found some huge and confusing answers that only left me but still lost. I really need some help

    
asked by anonymous 02.03.2017 / 17:56

1 answer

3

Here is an example implementation of the feature that selects a gallery image and moves to another directory:

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class MainActivity extends AppCompatActivity {


    /**
     * Diretótio onde vamos salvar
     */
    private static final String DIRETORIO = "/app/imagens/";
    /**
     * Código de retono da galeria
     */
    private static final int IMAGEM_INTERNA = 123;

    /**
     * Código de retrono da permissão
     */
    private static final int CODE_PERMISSION = 12;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button.class.cast(findViewById(R.id.openGallery)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, IMAGEM_INTERNA);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        //cehaca a permissão!
        checkPermission();
    }

    /**
     * Método responsável por verificar se o app possui a permissão de escrita e leitura
     */
    private void checkPermission() {
        // Verifica necessidade de verificacao de permissao
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // Verifica necessidade de explicar necessidade da permissao
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this,"É necessário a  de leitura e escrita!", Toast.LENGTH_SHORT).show();
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE },
                        CODE_PERMISSION);
            } else {
                // Solicita permissao
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE,  android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        CODE_PERMISSION);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        // Se o resultado for OK e se trarar da rquisição IMAGEM INTERNA, então vamos tratar!
        if(resultCode == RESULT_OK && requestCode == IMAGEM_INTERNA){
            //Pegamos a URI da imagem...
            Uri uriSelecionada = intent.getData();

            // criamos um File com o diretório selecionado!
            final File selecionada = new File(getRealPathFromURI(uriSelecionada));
            /**
             *  Caso não exista o doretório, vamos criar!
             */
            final File rootPath  = new File(android.os.Environment.getExternalStorageDirectory()+DIRETORIO);
            if(!rootPath.exists()){
                rootPath.mkdirs();
            }

            /**
             * Criamos um file, com o no DIRETORIO, com o mesmo nome da anterior
             */
            final File novaImagem = new File(rootPath, selecionada.getName());

            //Movemos o arquivo!
            try {
                moveFile(selecionada, novaImagem);
                Toast.makeText(getApplicationContext(), "Imagem movida com sucesso!", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

    }

    /**
     * Copia a imagem e remove o destino
     */
    private void moveFile(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();
        }
        //Alertamos, caso não consiga remover
        if(!sourceFile.delete()){
            Toast.makeText(getApplicationContext(), "Não foi possível remover a imagem!", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * Transforma o Uri em um diretório válido, para carregarmos em um arquivo
     * @param contentUri
     * @return
     */
    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);
    }


}

Remember that it is necessary to declare the following uses-permission in its AndroidManifest.xml :

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

font a>

    
02.03.2017 / 19:02