decode Sampled Bitmap From Self - Android Graphics

Android examples for Graphics:Bitmap Sample Size

Description

decode Sampled Bitmap From Self

Demo Code


//package com.java2s;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

public class Main {
    public static Bitmap decodeSampledBitmapFromSelf(Bitmap srcBitmap,
            int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.outWidth = srcBitmap.getWidth();
        options.outHeight = srcBitmap.getHeight();
        int inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);//from  w  w w.  j  ava  2  s .  c  o  m

        Bitmap.Config config = srcBitmap.getConfig();
        Bitmap copyBitmap = Bitmap.createBitmap(srcBitmap.getWidth(),
                srcBitmap.getHeight(), config);
        Matrix matrix = new Matrix();

        matrix.setScale(1.0f / inSampleSize, 1.0f / inSampleSize);
        new Canvas(copyBitmap).drawBitmap(srcBitmap, matrix, new Paint());
        return copyBitmap;
    }

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

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

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize; 
    }
}

Related Tutorials