get Scaled Bitmap Picture - Android Graphics

Android examples for Graphics:Bitmap Resize

Description

get Scaled Bitmap Picture

Demo Code

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class Main {
  private static final String TAG = "CameraUtil";

  public static String getScaledPicture(String picturePath, int targetDim) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;//from   www  .  j  av  a  2s.c o  m

    BitmapFactory.decodeFile(picturePath, opts);
    int photoW = opts.outWidth;
    int photoH = opts.outHeight;

    int scaleFactor = Math.max(photoW / targetDim, photoH / targetDim);

    opts.inJustDecodeBounds = false;
    opts.inSampleSize = scaleFactor;
    opts.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(picturePath, opts);
    Log.v(TAG,
        "scaled image size: " + bitmap.getWidth() + ", " + bitmap.getHeight());
    return saveImage(bitmap);
  }

  public static String saveImage(Bitmap bmp) {
    try {
      File fo = getOutputFile();
      FileOutputStream fos = new FileOutputStream(fo);
      try {
        bmp.compress(CompressFormat.JPEG, 90, fos);
        return fo.getAbsolutePath();
      } finally {
        fos.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  static File getOutputFile() {
    File storage = new File(Environment.getExternalStorageDirectory(),
        "BasinMirror");
    storage.mkdirs();
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
        Locale.getDefault()).format(new Date());
    return new File(storage, "IMG_" + timestamp + ".jpg");
  }
}

Related Tutorials