scale bitmap to fit to MAX_WIDTH x MAX_HEIGHT bounding box - Android Graphics

Android examples for Graphics:Bitmap Resize

Description

scale bitmap to fit to MAX_WIDTH x MAX_HEIGHT bounding box

Demo Code


//package com.java2s;

import android.graphics.Bitmap;

import android.graphics.Matrix;

public class Main {
    /**/*from w w w  .j a  va2 s  .co m*/
     * max picture width
     */
    private static final int MAX_WIDTH = 400;
    /**
     * max picture height
     */
    private static final int MAX_HEIGHT = 300;

    /**
     * scale bitmap to fit to MAX_WIDTH x MAX_HEIGHT bounding box
     * 
     * @param source
     *            bitmap we want to scale
     * @return scaled bitmap
     */
    public static Bitmap scaleBitmap(Bitmap source) {
        float scale = Math.min(MAX_WIDTH / (float) source.getWidth(),
                MAX_HEIGHT / (float) source.getHeight());
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        Bitmap result = Bitmap.createBitmap(source, 0, 0,
                source.getWidth(), source.getHeight(), matrix, false);
        return result;
    }
}

Related Tutorials