Question

In my app I have a Gallery-similar functionality and faced the issue that I need to scale the images. My test device in Nexus 5 which has a screen width of 1080p (360dp). Below are screenshots of an image having a width of 604 pixels opened with my app and the system-default Gallery:

My app:

enter image description here

=============================

Gallery:

enter image description here

The code I use to show the image is quite simple:

    pathToImage = getIntent().getStringExtra("path");
    img = (ImageView) findViewById(R.id.imgPictureView);
    try {
        bmpImage = BitmapFactory.decodeFile(pathToImage);
        img.setImageBitmap(bmpImage);

    } catch (Exception e) {
        e.printStackTrace();
    }

Opening a hi-res camera photo causes my ImageView to adjust its width to fill the screen, however I'm getting a heap size of about 80 (!!) MB.

It's obvious that the system gallery decides whether to scale the Bitmap up/down to make it fit the screen. For example, it scales a 60px image up, but only by a small factor so it doesn't become really blurry. I guess it also scales large camera pictures down to prevent OutOfMemoryError's. So in my example above, the gallery assumed the width of 604px is enough to scale it up to 1080 without noticeable quality loss, my app of course not due to lack of any additional code.

So the question is: how can I achieve the same result and determine the factor to scale images up/down without quality loss depending on the current screen?

Note: for those who will now post tons of (beyond controversy amazing) code examples showing how to actually scale a Bitmap or determine the screen width - this is NOT my question.

Was it helpful?

Solution

Bitmap can use a lot of memory and you got to scale them down. Instead of giving you a copied solution, here's a detailed documentation:

http://developer.android.com/training/displaying-bitmaps/index.html

You really should go through the whole guide. There's a lot to learn.

Second, set your ImageView's width to MATCH_PARENT and try changing its scaleType attribute to centerCrop. Play with the other available values for scaleType to get your desired result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top