Search code examples
androidimagebitmapscale

How to scale down a bitmap image before loading into an imageview?


I'm using the below method to load images from the Android gallery, it works but if I select an image taken using the back camera(ie, large resolution) it won't load into the image view. It will load smaller images from the front camera without fail.

I'm guessing that the image needs to be scaled down to sucesfully load into the imageview.

Does anyone know how to scale down the image programatically?

I've commented out the createScaledBitmap line of code as I'm not sure how to implement it.

This is the complete method that gets an image from the gallery:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            if(data != null){
            ImageView imageView = (ImageView) findViewById(R.id.capturedDebriImageView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            //imageView.setImageBitmap(Bitmap.createScaledBitmap(picturePath, 130, 110, false));
            }
            else if(data == null){
                 Toast.makeText(this, "Callout for image failed!", 
                         Toast.LENGTH_LONG).show();

            }


        }
    }

Solution

  • You need to load the image into one Bitmap, then create a second scaled down bitmap from the first:

    Bitmap bmp = BitmapFactory.decodeFile(picturePath);
    imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 130, 110, false));
    bmp.recycle();
    

    This method allows you to scale the bitmap to an arbitrary width and height. If you don't need it to be an exact size then using inSampleSize as per the other answer is more efficient, but you can only scale by powers of 2.