get Decoded Bitmap for target width and height - Android Graphics

Android examples for Graphics:Bitmap Size

Description

get Decoded Bitmap for target width and height

Demo Code


//package com.java2s;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

public class Main {
    public static Bitmap getDecodedBitmap(String path, float target_width,
            float target_height) {
        Options decode_options = new Options();
        decode_options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, decode_options); //This will just fill the output parameters
        int inSampleSize = calculateInSampleSize(decode_options,
                target_width, target_height);

        Options outOptions = new Options();
        outOptions.inJustDecodeBounds = false;
        outOptions.inSampleSize = inSampleSize;
        outOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
        outOptions.inScaled = false;//from  w  w  w. ja  v a2s . c  o  m

        Bitmap decodedBitmap = BitmapFactory.decodeFile(path, outOptions);
        Bitmap outBitmap = Bitmap.createScaledBitmap(
                decodedBitmap,// (int)target_width, (int)target_height, true);
                (int) ((float) decodedBitmap.getWidth() / inSampleSize),
                (int) ((float) decodedBitmap.getHeight() / inSampleSize),
                true);


        return outBitmap;
    }

    public static int calculateInSampleSize(Options options,
            float reqWidth, float reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

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

            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width
                    / (float) reqWidth);

            inSampleSize = heightRatio < widthRatio ? heightRatio
                    : widthRatio;
        }

        return inSampleSize;
    }
}

Related Tutorials