compress Bitmap Image - Android Graphics

Android examples for Graphics:Bitmap Read

Description

compress Bitmap Image

Demo Code

//package com.java2s;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

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

public class Main {

    private static Bitmap comp(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(CompressFormat.JPEG, 100, baos);
        if (baos.toByteArray().length / 1024 > 1024) {// 1M,BitmapFactory.decodeStream
            baos.reset();// baosbaos
            image.compress(CompressFormat.JPEG, 50, baos);// 50%baos
        }//from   www .j av  a 2s.co  m
        ByteArrayInputStream isBm = new ByteArrayInputStream(
                baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // options.inJustDecodeBounds true
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 800*480
        float hh = 800f;// 800f
        float ww = 480f;// 480f
        // 
        int be = 1;// be=1
        if (w > h && w > ww) {// 
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 
        // options.inJustDecodeBounds false
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return compressImage(bitmap);// 
    }

    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(CompressFormat.JPEG, 100, baos);// 100baos
        int options = 100;
        while (baos.toByteArray().length / 1024 > 60) { // 100kb,
            baos.reset();// baosbaos
            image.compress(CompressFormat.JPEG, options, baos);// options%baos
            options -= 10;// 10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(
                baos.toByteArray());// baosByteArrayInputStream
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// ByteArrayInputStream
        return bitmap;
    }
}

Related Tutorials