crop And Scale Image - Android Graphics

Android examples for Graphics:Image Crop

Description

crop And Scale Image

Demo Code


//package com.java2s;

import android.graphics.Bitmap;

import android.graphics.Matrix;

public class Main {
    public static Bitmap cropAndScaleImage(Bitmap bitmap, int width,
            int height) {
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Bitmap resized = null;//from w  w w  . ja v a  2 s  .c  om
        if (mWidth < width) {
            float scale = width / mWidth;
            resized = myScale(bitmap, scale);
        } else {
            resized = bitmap;
        }
        if (mHeight < height) {
            float scale = height / mHeight;
            resized = myScale(resized, scale);
        } else {
            resized = bitmap;
        }
        int mX = Math.abs((mWidth - width) / 2);
        int mY = Math.abs(mHeight - mWidth / 2);

        return Bitmap.createBitmap(resized, mX, mY, mWidth - mX, mHeight
                - mY);
    }

    public static Bitmap myScale(Bitmap bitmap, float scale) {
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, false);
    }
}

Related Tutorials