get Small Bitmap - Android Graphics

Android examples for Graphics:Bitmap Scale

Description

get Small Bitmap

Demo Code


//package com.java2s;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Main {

    public static Bitmap getSmallBitmap(String filePath, int sampleSize) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, sampleSize,
                sampleSize);//from   w  w w  .  jav a2s  .c o  m

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        Bitmap bm = BitmapFactory.decodeFile(filePath, options);
        if (bm == null) {
            return null;
        }
        //bm = ThumbnailUtils.extractThumbnail(bm, sampleSize, sampleSize, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);

        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            int quality = 30;
            bm.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            while (baos.toByteArray().length / 1024 > 5) {
                baos.reset();
                quality -= 5;
                bm.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            }

        } finally {
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bm;

    }

    private 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 heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width
                    / (float) reqWidth);

            inSampleSize = heightRatio < widthRatio ? widthRatio
                    : heightRatio;
        }

        return inSampleSize;
    }
}

Related Tutorials