Get the dimensions of an image in Android?


I'm trying to work with the width and height of an image.

I use this code to get the image, convert it into a Bitmap and then into base64.

private void PickFile(){
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        try {
                    Intent.createChooser(intent, "Selecciona app de galería."),
        }catch (android.content.ActivityNotFoundException ex){

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode){
            case PICKER:
                if (requestCode == 1){
                    foto = "foto";
                    Bitmap photobmp= null;

                    //String[] proj = { MediaStore.Images.Media.DATA };

                    Uri selectdImageUri = data.getData();

                    //String dataFU  = getRealPathFromURI(selectdImageUri);

                    photobmp = ((BitmapDrawable)img.getDrawable()).getBitmap();

                    int alto = photobmp.getWidth();
                    int ancho = photobmp.getHeight();
                    Toast.makeText(getApplicationContext(), alto+" "+ ancho +"", Toast.LENGTH_LONG).show();

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    byte[] imageBytes = baos.toByteArray();
                    encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                    Toast.makeText(getApplicationContext(), photobmp +"", Toast.LENGTH_LONG).show();
                } else{
                    Toast.makeText(getApplicationContext(),  "No se pudo extraer la imagen", Toast.LENGTH_SHORT).show();

I'm showing the width and height in Toast , to see if the data is correct, and that's where my problem is. When I choose an image, it shows me the wrong height and width and when I choose another image the Toast shows me the size of the previous image, it does not show me the size of the image I am visualizing.

Any suggestions on how I can show the correct data?

For example, here is showing the wrong data, those are not the height or width of the image.

Here the data of the other image is displayed, not the data of the selected image.

asked by jaron cascante Pérez 21.11.2016 в 19:03

1 answer


I solved it, the error was in this code:

photobmp = ((BitmapDrawable)img.getDrawable()).getBitmap();

I had to use "BitmapFactory", like this:

photobmp = BitmapFactory.decodeFile(dataFU);
answered by 21.11.2016 / 20:24