How to Save Path of a Photo Taken from Camera on Phone in Path or String

Asked

Viewed 6,687 times

5

I need to take the path that was saved the image and save it so that whenever I launch the app appears the image in an Imageview. my code is this

 public void onClickCamera(View v){
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap)data.getExtras().get("data");        
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageBitmap(photo);}}
  • I recommend taking a look at disk Storage. Here is a link with examples: http://developer.android.com/training/basics/data-storage/files.html

2 answers

5


Once I went through the same obstacle, searching a little I found a code on Soen that solved my problem and I believe it solves yours too:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageBitmap(photo);
        knop.setVisibility(Button.VISIBLE);


        // Chame este método pra obter a URI da imagem
        Uri uri = getImageUri(getApplicationContext(), photo);

        // Em seguida chame este método para obter o caminho do arquivo
        File file = new File(getRealPathFromURI(uri));

        System.out.println(file.getPath());
    }  
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    cursor.moveToFirst(); 
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(idx); 
}
  • Thank you so much I was having a hard time on this part!

1

@Guilherme you executed your code from a Samsung phone? Because I do not know if they are at all but on some mobiles Samsung occurs a bug saying that data of the method onActivityResult returns null. I will show you how to get the URI of the photo that has just been taken based on the code that google provides on: Android API Gui for Camera

/**
  * (ISTO é uma variável de instância) Contem o caminho e o nome do arquivo onde desejamos salvar a imagem. 
  * Usado principalmente para iniciar uma Intent.Action_View com esta URI. (GalleryApp)
  */
private Uri uriImagem = null;

public void onClickCamera(View v){
    // Cria uma intent para capturar uma imagem e retorna o controle para quem o chamou (NAO PRECISA DECLARAR PERMISSAO NO MANIFESTO PARA ACESSAR A CAMERA POIS O FAZEMOS VIA INTENT).
    Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
    // Cria um arquivo para salvar a imagem.
    uriImagem = ProcessaImagens.getOutputMediaFileUri( ProcessaImagens.MEDIA_TYPE_IMAGE, getActivity().getApplicationContext() );
    // Passa para intent um objeto URI contendo o caminho e o nome do arquivo onde desejamos salvar a imagem. Pegaremos atraves do parametro data do metodo onActivityResult().
    intent.putExtra( MediaStore.EXTRA_OUTPUT, uriImagem );
    // Inicia a intent para captura de imagem e espera pelo resultado.
    startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );
}

The class Image processing was a class I made and will be sharing with everyone. You can use this class at will. It has a very good image compression method in case you want to save images in the database. In your methodonActivityResult do this:

@Override
public void onActivityResult( int requestCode, int resultCode, Intent data ) {
    // Se finalizou a activity em startForActivityResult.
    if ( resultCode == Activity.RESULT_OK ) {
        if ( requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE ) {
            String imagemPath = uriImagem.getPath();
            // Vou compactar a imagem, leia o javadoc do médoto e verá que ela retorna tanto um bitmap como um array de bytes.
            List<Object> imagemCompactada = ProcessaImagens.compactarImagem( uriImagem.getPath() );
            Bitmap imagemBitmap = (Bitmap) imagemCompactada.get( 0 );
            byte[] imagemBytes = (byte[]) imagemCompactada.get( 1 );

        }
    }
    // Se cancelou a activity em startForActivityResult.
    else if ( resultCode == Activity.RESULT_CANCELED ) {
        if ( requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE ) {
            // Usuario cancelou a captura da imagem.
            Log.d( getTag(), "Captura de imagem CANCELADA!" );
        }
    }
    // Se ocorreu algum erro na activity em startForActivityResult.
    else {
        // Captura da imagem falhou, avisa ao usuario.
        Toast.makeText( getActivity().getApplicationContext(), "FALHA! A captura da imagem falhou!", Toast.LENGTH_LONG ).show();
        Log.e( getTag(), "FALHA! A captura da imagem falhou!" );
    }
}

Note that I used getActivity().getApplicationContext() because I am getting the context from a Fragment and not from an Activity. I believe that with this method you can get what you want. Just make the necessary changes as the way to get context. The way to get the TAG to display in logs etc.

  • This is Lucas! Your class has been helping me a lot. But the need arose to get a miniature bitmap, and so I’m trying to use one of the methods of its class, getMiniaturaImage, as you said it cannot run in the UI, I’m trying unsuccessfully as follows:new Thread(new Runnable() { @Override public void run() { imagemBitmap = (Bitmap) Image processing.getMiniaturaImage(getContentResolver(), uriImagem.getPath(), resultCode); } }). start();

  • Ele dá esse erro:java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} &#xA;to activity {br.com.singlepoint.crm.mobile/br.com.singlepoint.crm.mobile.activity.ChecklistActivity}: java.lang.IllegalStateException: Unknown URL: content://media/Xternal/images/media/-1? blocking=1&orig_id=-1&group_id=0

  • Can you ask a new question and post parts of your code for better viewing? Then you send me the link of your question here for me to follow and try to help. By comment it gets harder. I look forward to your answer.

  • If you can help, thank you very much: http://answall.com/questions/104594/generating

  • I would like the Image Processing class, the Lucas link is offline :/

Browser other questions tagged

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