Set Imageview content via a URI

Asked

Viewed 1,827 times

1

Guys, I’m trying to set the image in Imageview of my second Activity through a URI that comes from the first Activity but so far without success. What could be wrong?

File diretorio = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

      String nomeImagem = diretorio.getPath() + "/" + System.currentTimeMillis()+".jpg"; 

      uri = Uri.fromFile(new File(nomeImagem)); 

@Edit

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);  
    startActivityForResult(intent,CAPTURAR_IMAGEM);

 public void chamarTela(){
    Bundle dados = new Bundle();
    dados.putString("foto",uri.getPath().toString());
    Intent intent = new Intent(this,TelaPraVerImagem.class);
    intent.putExtras(dados);
    startActivity(intent);
}


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

    imageView = (ImageView) findViewById(R.id.foto);
    //imageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
   // TextView textView = (TextView)findViewById(R.id.mensagem);
    Intent intent = getIntent();
    if (intent != null){
        if(intent.getExtras() != null){
           Bundle dados = intent.getExtras();
           String  imgpath = dados.getString("foto");
           Uri uri = Uri.parse(imgpath);
           imageView.setImageURI(uri);


        }
    }
}

1 answer

2

Use the setImageUri() is not the best way to set image in your UI, it may cause some latency flaws when giving the Code.

Instead, use the setImageBitmap():

//Transforme sua URI em um Bitmap
Bitmap myImg = BitmapFactory.decodeFile(uri.getPath()); 
imgView.setImageBitmap(myImg);

@Edit

I suspect that the getPath() is not returning the true path of your image. When you access the path via getPath(), the return would be more or less this:

.\file image.jpg

PS: the URI class implements an Parcelable, that is, you can extract it directly from your Intent.

Try this:

public void chamarTela(){
    Intent intent = new Intent(this,TelaPraVerImagem.class);
    intent.putExtra("foto", uri);
    startActivity(intent);
}

...
Intent intent = getIntent();
    if (intent != null){
        if(intent.getExtras() != null){
            Uri uri = intent.getParcelableExtra("foto");
            Bitmap myImg = BitmapFactory.decodeFile(uri.getPath().getAbsolutePath()); 
            imgView.setImageBitmap(myImg);
        }
    }

@Edit2

Following the Google documentation, I believe that you really are putting the wrong path when creating the image

Follow the code with some comments:

String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Criando o nome de uma imagem. Você pode seguir o padrão Brasil aqui
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    //Um detalhe aqui, não é garantido que o device tenha um getExternalStoragePublicDirectory(), 
    //É importante você fazer esta validação
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefixo */
        ".jpg",         /* sufixo */
        storageDir      /* diretorio */
    );

    // Esse é o path que você vai utilizar na resposta da sua Intent
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}


static final int REQUEST_TAKE_PHOTO = 1;

private void chamarTela() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Criando um File que aponta onde sua foto deve ir
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            ...
        }
        // Continua apenas se sua foto foi salva de verdade
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

private void setPic() {
    // Pegando as dimensões de sua View
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    // Pegando as dimensões do Bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determinando o quanto que deve diminuir de tamanho/qualidade
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

    // Garantindo que o Bitmap fique boa dentro de uma View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    imgView.setImageBitmap(bitmap);
}
  • I changed it, but still the image doesn’t show.

  • What is the origin of the URI? Web or internal link?

  • @Wakim It is internal Uri = Uri.fromFile(new File(filename));

  • Could you include a sample? Is that of the image schema, can have a different treatment.

  • @Wakim Ok, sample added!

  • Edited response!

  • @sicachester followed its procedure but still does not appear the image, but I set up a text view to know the path that is coming this /Storage/Emulated/0/Pictures/1410183174.jpg

  • @user8398 the problem is that you are giving a Uri.fromFile(new File(nomeImagem)), but this line of code does not create the image itself. Where are you writing/saving this image?

  • @sicachester then, this Uri.fromFile(new File(filename)) is to reference the photo that was taken with the Intent call Intent = new Intent(Mediastore.ACTION_IMAGE_CAPTURE);

  • @Renan you are passing the image with the way in time to call the Intent(MediaStore.ACTION_IMAGE_CAPTURE)? Includes full call please

  • @sicachester I edited, take a look!

  • @Renan edited the answer. I believe that now you can do what you want. I put in the comments a detail about the getExternalStoragePublicDirectory() that you should stay tuned

  • @sicachester I think I understand wrong, because my doubt in this code is the following, in what part are you sending this image to the second Activity that has only one Imageview? In the first code I posted the image is being saved yes, because I send a broadcast to actually add the image in the gallery.

Show 8 more comments

Browser other questions tagged

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