get Compress Image By Save Path - Android android.graphics

Android examples for android.graphics:Image Load Save

Description

get Compress Image By Save Path

Demo Code

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();
    newOpts.inJustDecodeBounds = true;//from   w  w  w. j  ava 2 s. c om
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;

    int pixel = w;
    if (w < h) {
      pixel = h;
    }
    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);
    int options = 100;
    while (baos.toByteArray().length / 1024 > 60) {
      baos.reset();
      image.compress(CompressFormat.JPEG, options, baos);
      options -= 10;
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
    return bitmap;
  }

}

Related Tutorials