nagylzs
nagylzs

Reputation: 4180

How to load bitmap from res without resizing?

Using this code:

    Drawable blankDrawable = context.getResources().getDrawable(image);
    Bitmap blankBitmap=((BitmapDrawable)blankDrawable).getBitmap();

I get a bitmap that is scaled to the density of the context, preserving the physical size of the bitmap (based on its dpi value). So for example, I have a 405x500 bitmap (dpi=96) as a resource. But when I load it on a device, I get a 608x750 image with density=240. I want to load the bitmap without scaling. How do I do that?

This question is very similar to:

How to create a Drawable from a stream without resizing it?

However, that solution cannot be used in my case, because I don't have an input stream. All I have is a resource id, and the getDrawable() method does not have parameters for density. Once the bitmap is loaded, it is too late - it was already resized.

Thank you.

Upvotes: 18

Views: 28880

Answers (5)

RajaReddy PolamReddy
RajaReddy PolamReddy

Reputation: 22493

use this

InputStream is = this.getResources().openRawResource(imageId);
Bitmap originalBitmap = BitmapFactory.decodeStream(is);  
imageview.setImageBitmap(originalBitmap);

Upvotes: 30

nmr
nmr

Reputation: 16850

Another good option may be to put the bitmap in the drawable-nodpi resource folder

Upvotes: 7

Chirry
Chirry

Reputation: 680

When you're decoding the bitmap with

BitmapFactory.decodeResource (Resources res, int id, BitmapFactory.Options opts) 

Set the flag inScaled in BitmapFactory.Options to false first.

Example:

/* Set the options */
Options opts = new Options();
opts.inDither = true;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
opts.inScaled = false; /* Flag for no scalling */ 


/* Load the bitmap with the options */
bitmapImage = BitmapFactory.decodeResource(context.getResources(),
                                           R.drawable.imageName, opts);

Upvotes: 16

Nikunj Patel
Nikunj Patel

Reputation: 22066

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ImageView image = (ImageView) findViewById(R.id.test_image);
    Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
    image.setImageBitmap(bMap);
}

First create an ImageView instance containing the ImageView from the layout. Then create a bitmap from the application icon (R.drawable.icon) with BitmapFactory.decodeResource(). Finally set the new bitmap to be the image displayed in the ImageView component of the layout.

Upvotes: 2

Walid Hossain
Walid Hossain

Reputation: 2714

Create a drawable (without hdpi/mdpi etc) folder in res. Keep the drawable in that folder. Now try it. This may help you.

Upvotes: 2

Related Questions