androidandroid-canvasandroid-drawableandroid-bitmapbitmapfactory

How to get Bitmap with actual size of it, in Bitmap variable irrespective of deivce I am using


I have a jpg image of size 1080*1080 in my drawable folder, when I am storing it in a Bitmap variable the size of the bitmap is not showing as 1080*1080, it is showing based on the device I am using, I want to draw the actual image with size 1080*1080 on a canvas, any idea how to get the bitmap with actual size

    Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.template_image);
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

The variable w and h are not showing 1080*1080, it's different on different devices


Solution

  • put your image file in drawable-nodpi This folder tells android to avoid scaling your image file on any pixel density:

    More Info Medium Article

    If you need to only retrieve image size without showing inside image view:

    BitmapFactory.Options options = new BitmapFactory.Options();
    //Just Retreive info about the bitmap without loading inside memory to avoid OutOfMemory.
    options.inJustDecodeBounds(true)
    Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.template_image, options);
    int w = options.outWidth;
    int h = options.outHeight;