Android Bitmap Create getBitmapFromResource(Resources resources, int resourceId, int reqWidth, int reqHeight)

Here you can find the source of getBitmapFromResource(Resources resources, int resourceId, int reqWidth, int reqHeight)

Description

get Bitmap From Resource

Declaration

public static Bitmap getBitmapFromResource(Resources resources,
            int resourceId, int reqWidth, int reqHeight) 

Method Source Code

//package com.java2s;
import android.content.res.Resources;
import android.graphics.Bitmap;

import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

public class Main {
    public static Bitmap getBitmapFromResource(Resources resources,
            int resourceId, int reqWidth, int reqHeight) {
        // Set options
        BitmapFactory.Options options = new BitmapFactory.Options();

        // Fetch Image bounds (width/height)
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resourceId, options);

        // Calculate Sample Size based upon required height and width
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);//from   w  w  w  . j  a  v a  2s  . c o  m
        options.inJustDecodeBounds = false;

        // Fetch bitmap
        Bitmap image = BitmapFactory.decodeResource(resources, resourceId,
                options);
        return image;
    }

    private static int calculateInSampleSize(Options options, int reqWidth,
            int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width
                    / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio
                    : widthRatio;
        }

        return inSampleSize;
    }
}

Related

  1. createCompatibleImage(int width, int height)
  2. createCompatibleImage(BufferedImage image, int width, int height)
  3. getBitMapFromStream(String filename)
  4. getBitmap(int resId, Context ctx)
  5. getBitmapFromImageView(ImageView theImage)
  6. getBitmapFromURI(Context context, Uri uri)
  7. getBackground(int bgcolor)
  8. makeBitmap(int minSideLength, int maxNumOfPixels, Uri uri, ContentResolver cr, ParcelFileDescriptor pfd, BitmapFactory.Options options)
  9. generateBitmap(int width, int height)