decode Sampled Bitmap From Resource - Android android.graphics

Android examples for android.graphics:Bitmap Load Save

Description

decode Sampled Bitmap From Resource

Demo Code

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

public class Main {

  public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*from w w  w . j a  v a 2 s. c  o m*/
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(path, options);
  }

  public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    int inSampleSize = 1;
    if (options.outHeight > reqHeight || options.outWidth > reqWidth) {
      final int halfHeight = options.outHeight / 2;
      final int halfWidth = options.outWidth / 2;
      while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
      }
    }
    return inSampleSize;
  }

}

Related Tutorials