resize Bitmap By Center Crop - Android Graphics

Android examples for Graphics:Bitmap Crop

Description

resize Bitmap By Center Crop

Demo Code


//package com.java2s;

import android.graphics.Bitmap;

import android.graphics.Matrix;

public class Main {

    public static Bitmap resizeBitmapByCenterCrop(Bitmap src,
            int containerWidth, int containerHeight) {

        if (src == null || containerWidth == 0 || containerHeight == 0) {
            return null;
        }/*from   w  w  w.j a va2  s .c  o  m*/

        int bitmapWidth = src.getWidth();
        int bitmapHeight = src.getHeight();

        float widthRatio = (float) containerWidth / (float) bitmapWidth;
        float heightRatio = (float) containerHeight / (float) bitmapHeight;

        Bitmap scaleUpBitmap = widthRatio > heightRatio ? getScaleBitmap(
                src, widthRatio) : getScaleBitmap(src, heightRatio);

        int firstPixelX = (scaleUpBitmap.getWidth() - containerWidth) / 2;
        int firstPixelY = (scaleUpBitmap.getHeight() - containerHeight) / 2;
        return Bitmap.createBitmap(scaleUpBitmap, firstPixelX, firstPixelY,
                containerWidth, containerHeight);
    }

    public static Bitmap getScaleBitmap(Bitmap mBitmap, float scaleRatio) {
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(scaleRatio, scaleRatio);
        Bitmap mScaleBitmap = Bitmap.createBitmap(mBitmap, 0, 0, width,
                height, matrix, true);

        return mScaleBitmap;
    }
}

Related Tutorials