Grab an Image from the gallery and move to a folder

Asked

Viewed 917 times

0

I’m using the following code to pick up 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 take the image path and move to the folder "/app/imagens/" which is in the internal memory.

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

I found the following code on the web and works well 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 have read several posts of Google itself and I did not reach any conclusion, I was looking for the stack overflow (in English).

I found some huge and confusing answers that just left me lost yet. I really need some help

  • you want the only way to save the image?

  • Move to another direction

  • guess q missing java tag

  • @Efferson, patience is a virtue friend!

1 answer

3


Here is an example of the implementation of the functionality that selects an image from the gallery 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 his AndroidManifest.xml:

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

source

  • Very sheltered!! It worked perfectly!

  • I created the selected variable before the onCreate() no longer final and then I selecionada as in the example so I can send the image path to the model and then register in the sqlite, but how can I set this path in a ImageView or in a ImageButton?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.