Compress the image size with JPEG format limit to the maxSize(kb). - Android Graphics

Android examples for Graphics:Image Compress

Description

Compress the image size with JPEG format limit to the maxSize(kb).

Demo Code


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

public class Main {
    /**//from   ww  w  .ja v a  2  s. co  m
     * Compress the image size with JPEG format limit to the maxSize(kb).
     * @param image
     * @param maxSize
     * @return
     */
    public static Bitmap compressImage(Bitmap image, int maxSize) {
        byte[] bytes = compressImage(image, Bitmap.CompressFormat.JPEG,
                maxSize);
        ByteArrayInputStream isBm = new ByteArrayInputStream(bytes);
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    /**
     * Compress the image size limit to the maxSize(kb).
     * @param image
     * @param compressFormat
     * @param maxSize
     * @return
     */
    public static byte[] compressImage(Bitmap image,
            Bitmap.CompressFormat compressFormat, int maxSize) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        image.compress(compressFormat, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > maxSize) {
            baos.reset();
            image.compress(compressFormat, options, baos);
            if (options <= 10) {
                options -= 2;
            } else {
                options -= 10;
            }
        }
        return baos.toByteArray();
    }
}

Related Tutorials