Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load bitmap from res without resizing?

Tags:

android

bitmap

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.

like image 611
nagylzs Avatar asked Oct 01 '11 08:10

nagylzs


People also ask

How do you handle bitmap in Android as it takes too much memory?

Choose the most appropriate decode method based on your image data source. These methods attempt to allocate memory for the constructed bitmap and therefore can easily result in an OutOfMemory exception. Each type of decode method has additional signatures that let you specify decoding options via the BitmapFactory.

How do I create a bitmap from resources?

To create a bitmap from a resource, you use the BitmapFactory method decodeResource(): Bitmap bitmap = BitmapFactory. decodeResource(getResources(), R. drawable.

What is inJustDecodeBounds?

inJustDecodeBounds. If set to true, the decoder will return null (no bitmap), but the out... public boolean. inMutable. If set, decode methods will always return a mutable Bitmap instead of an immutable one.


3 Answers

use this

InputStream is = this.getResources().openRawResource(imageId);
Bitmap originalBitmap = BitmapFactory.decodeStream(is);  
imageview.setImageBitmap(originalBitmap);
like image 82
RajaReddy PolamReddy Avatar answered Oct 06 '22 13:10

RajaReddy PolamReddy


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);
like image 16
Chirry Avatar answered Oct 06 '22 11:10

Chirry


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

like image 7
nmr Avatar answered Oct 06 '22 11:10

nmr