Search code examples
androidandroid-imageviewandroid-imageandroid-bitmapandroid-background

How to retrieve multiple images from Res/draw using BitmapFactory.decodeResource


I need to resize images according to the device screen size.I can do it for single images one at a time,Currently I am dealing with 18 images.The code will be too clumsy and difficult to work out with. Most importantly in my code I need to create a matrix to store the image once created . I am following this link Resize Bitmap image?.

How can I load multiple images so that I can do it easily and more efficiently.


Solution

  • @SuppressLint("NewApi")
        public static int getDeviceWidth(Activity activity) {
            int deviceWidth = 0;
    
            Point size = new Point();
            WindowManager windowManager = activity.getWindowManager();
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                windowManager.getDefaultDisplay().getSize(size);
                deviceWidth = size.x;
            } else {
                Display display = windowManager.getDefaultDisplay();
                deviceWidth = display.getWidth();
            }
            return deviceWidth;
        }
    
        @SuppressLint("NewApi")
        public static int getDeviceHeight(Activity activity) {
            int deviceHeight = 0;
    
            Point size = new Point();
            WindowManager windowManager = activity.getWindowManager();
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                windowManager.getDefaultDisplay().getSize(size);
                deviceHeight = size.y;
            } else {
                Display display = windowManager.getDefaultDisplay();
                deviceHeight = display.getHeight();
            }
            return deviceHeight;
        }
    

    //above function get device width and height

    public static Bitmap getBitmapFromPath(String sdCardPath, Activity activity) {
            // TODO Auto-generated method stub
            return decodeSampledBitmapFromResource(sdCardPath,
                    getDeviceWidth(activity), getDeviceHeight(activity));
        }
    

    base on getBitmapFromPath() you can set your image as device specific.. call getBitmapFromPath() in your activity when you retrieve path of image.

    //edited answer

    final R.drawable drawableResources = new R.drawable();
    final Class<R.drawable> c = R.drawable.class;
    final Field[] fields = c.getDeclaredFields();
    
    for (int i = 0, max = fields.length; i < max; i++) {
        final int resourceId;
        try {
            resourceId = fields[i].getInt(drawableResources);
        } catch (Exception e) {
            continue;
        }
        /* make use of resourceId for accessing Drawables here */
    }