get Compress Bitmap Image By Save Path - Android Graphics

Android examples for Graphics:Bitmap Save

Description

get Compress Bitmap Image By Save Path

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 {

    public static Bitmap getCompressImageBySavePath(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // options.inJustDecodeBounds true
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// bm
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;

        int pixel = w;
        if (w < h) {
            pixel = h;/*w  w  w.  j a  va2 s.  c o m*/
        }
        int be = 1;// be=1
        if (pixel > 3000) {
            be = 4;
        } else if (pixel > 1600) {
            be = 2;
        }

        newOpts.inSampleSize = be;
        bitmap = BitmapFactory.decodeFile(srcPath, 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