Get Bitmap from Path - Android Graphics

Android examples for Graphics:Bitmap File

Description

Get Bitmap from Path

Demo Code


//package com.java2s;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {

    public static Bitmap getBitmapFromPath(String path, int w, int h) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options); 
        options.inSampleSize = calculateInSampleSize(options, w, h);
        options.inJustDecodeBounds = false;
        Bitmap bm = BitmapFactory.decodeFile(path, options);
        if (bm == null) {
            return null;
        }//from w  w  w.  j a  va 2s.c om
        return bm;
    }

    private static int calculateInSampleSize(BitmapFactory.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) {

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

            inSampleSize = heightRatio < widthRatio ? widthRatio
                    : heightRatio;
        }

        return inSampleSize;
    }
}

Related Tutorials