resize Bitmap Picture - Android Graphics

Android examples for Graphics:Bitmap Resize

Description

resize Bitmap Picture

Demo Code


//package com.java2s;

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

public class Main {
    public static Bitmap resizePicture(byte[] bytes, int targetWidth,
            int targetHeight) {
        Bitmap pic;/*from www. ja v a  2  s  .  c  o m*/
        BitmapFactory.Options bmpOptions = new BitmapFactory.Options();

        bmpOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bytes, 0, bytes.length, bmpOptions);

        int currHeight = bmpOptions.outHeight;
        int currWidth = bmpOptions.outWidth;

        int sampleSize = 1;

        if (currHeight > targetHeight || currWidth > targetWidth) {
            // use either width or height
            if (currWidth > currHeight)
                sampleSize = Math.round((float) currHeight
                        / (float) targetHeight);
            else
                sampleSize = Math.round((float) currWidth
                        / (float) targetWidth);
        }
        // use the new sample size
        bmpOptions.inSampleSize = sampleSize;

        // now decode the bitmap using sample options
        bmpOptions.inJustDecodeBounds = false;

        // get the file as a bitmap
        pic = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
                bmpOptions);
        return pic;
    }

    public static Bitmap resizePicture(String imgPath, int targetWidth,
            int targetHeight) {
        Bitmap pic;
        // create bitmap options to calculate and use sample size
        BitmapFactory.Options bmpOptions = new BitmapFactory.Options();

        // first decode image dimensions only - not the image bitmap
        // itself
        bmpOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imgPath, bmpOptions);

        int currHeight = bmpOptions.outHeight;
        int currWidth = bmpOptions.outWidth;

        int sampleSize = 1;

        if (currHeight > targetHeight || currWidth > targetWidth) {
            // use either width or height
            if (currWidth > currHeight)
                sampleSize = Math.round((float) currHeight
                        / (float) targetHeight);
            else
                sampleSize = Math.round((float) currWidth
                        / (float) targetWidth);
        }
        // use the new sample size
        bmpOptions.inSampleSize = sampleSize;

        // now decode the bitmap using sample options
        bmpOptions.inJustDecodeBounds = false;

        // get the file as a bitmap
        pic = BitmapFactory.decodeFile(imgPath, bmpOptions);
        return pic;
    }
}

Related Tutorials