compress Bitmap for required width and height - Android Graphics

Android examples for Graphics:Bitmap Compress

Description

compress Bitmap for required width and height

Demo Code


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.util.Log;

public class Main {

  public final static Bitmap compressBitmap(String path, int rqsW, int rqsH) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inDither = false;//from   w  w w  .  ja v a 2 s.c om
    options.inPurgeable = true;
    options.inTempStorage = new byte[12 * 1024];
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = caculateInSampleSize(options, rqsW, rqsH);
    options.inJustDecodeBounds = false;
    File file = new File(path);
    FileInputStream fs = null;
    try {
      fs = new FileInputStream(file);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    Bitmap bmp = null;
    if (fs != null)
      try {
        bmp = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, options);
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (fs != null) {
          try {
            fs.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    return bmp;
  }

  public final static String compressBitmap(Context context, String srcPath, int rqsW, int rqsH, boolean isDelSrc) {
    Bitmap bitmap = compressBitmap(srcPath, rqsW, rqsH);
    File srcFile = new File(srcPath);
    String desPath = getImageCacheDir(context) + srcFile.getName();
    int degree = getDegress(srcPath);
    try {
      if (degree != 0)
        bitmap = rotateBitmap(bitmap, degree);
      File file = new File(desPath);
      FileOutputStream fos = new FileOutputStream(file);
      bitmap.compress(Bitmap.CompressFormat.PNG, 30, fos);
      fos.close();
      if (isDelSrc)
        srcFile.deleteOnExit();
    } catch (Exception e) {
      // TODO: handle exception
      Log.e("BitmapHelper-->compressBitmap", e.getMessage() + "");
    }
    return desPath;
  }

  @Deprecated
  public final static Bitmap compressBitmap(InputStream is, int reqsW, int reqsH, boolean isAdjust) {
    Bitmap bitmap = BitmapFactory.decodeStream(is);
    return compressBitmap(bitmap, reqsW, reqsH, isAdjust);
  }

  public final static Bitmap compressBitmap(InputStream is, int reqsW, int reqsH) {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte[] bts = new byte[1024];
      int len = 0;
      while ((len = is.read(bts)) != -1) {
        baos.write(bts, 0, len);
        baos.flush();
      }
      byte[] bytes = baos.toByteArray();
      Bitmap bitmap = compressBitmap(bytes, reqsW, reqsH);
      is.close();
      baos.close();
      return bitmap;
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
      Log.e("BitmapHelper--inputstream", e.getMessage() + "");
      return null;
    }
  }

  public final static Bitmap compressBitmap(byte[] bts, int reqsW, int reqsH) {
    final Options options = new Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(bts, 0, bts.length, options);
    options.inSampleSize = caculateInSampleSize(options, reqsW, reqsH);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeByteArray(bts, 0, bts.length, options);
  }

  @Deprecated
  public final static Bitmap compressBitmap(Bitmap bitmap, int reqsW, int reqsH, boolean isAdjust) {
    if (bitmap == null || reqsW == 0 || reqsH == 0)
      return bitmap;
    if (bitmap.getWidth() > reqsW || bitmap.getHeight() > reqsH) {
      float scaleX = new BigDecimal(reqsW).divide(new BigDecimal(bitmap.getWidth()), 4, RoundingMode.DOWN).floatValue();
      float scaleY = new BigDecimal(reqsH).divide(new BigDecimal(bitmap.getHeight()), 4, RoundingMode.DOWN)
          .floatValue();
      if (isAdjust) {
        scaleX = scaleX < scaleY ? scaleX : scaleY;
        scaleY = scaleX;
      }
      Matrix matrix = new Matrix();
      matrix.postScale(scaleX, scaleY);
      bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }
    return bitmap;
  }

  public final static Bitmap compressBitmap(Bitmap bitmap, int reqsW, int reqsH) {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      bitmap.compress(CompressFormat.PNG, 100, baos);
      byte[] bts = baos.toByteArray();
      Bitmap res = compressBitmap(bts, reqsW, reqsH);
      baos.close();
      return res;
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return bitmap;
    }
  }

  @Deprecated
  public final static Bitmap compressBitmap(Resources res, int resID, int reqsW, int reqsH, boolean isAdjust) {
    Bitmap bitmap = BitmapFactory.decodeResource(res, resID);
    return compressBitmap(bitmap, reqsW, reqsH, isAdjust);
  }

  public final static Bitmap compressBitmap(Resources res, int resID, int reqsW, int reqsH) {
    final Options options = new Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resID, options);
    options.inSampleSize = caculateInSampleSize(options, reqsW, reqsH);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resID, options);
  }

  public final static Bitmap compressBitmap(Bitmap bitmap, long maxBytes) {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      bitmap.compress(CompressFormat.PNG, 100, baos);
      int options = 90;
      while (baos.toByteArray().length > maxBytes) {
        baos.reset();
        bitmap.compress(CompressFormat.PNG, options, baos);
        options -= 10;
      }
      byte[] bts = baos.toByteArray();
      Bitmap bmp = BitmapFactory.decodeByteArray(bts, 0, bts.length);
      baos.close();
      return bmp;
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }

  /**
   * caculate the bitmap sampleSize
   * 
   * @param path
   * @return
   */
  public final static int caculateInSampleSize(BitmapFactory.Options options, int rqsW, int rqsH) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (rqsW == 0 || rqsH == 0)
      return 1;
    if (height > rqsH || width > rqsW) {
      final int heightRatio = Math.round((float) height / (float) rqsH);
      final int widthRatio = Math.round((float) width / (float) rqsW);
      inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    return inSampleSize;
  }

  private static String getImageCacheDir(Context context) {
    String dir = "Image" + File.separator;
    File file = new File(dir);
    if (!file.exists())
      file.mkdirs();
    return dir;
  }

  /**
   * get the orientation of the bitmap {@link android.media.ExifInterface}
   * 
   * @param path
   * @return
   */
  public final static int getDegress(String path) {
    int degree = 0;
    try {
      ExifInterface exifInterface = new ExifInterface(path);
      int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
      switch (orientation) {
      case ExifInterface.ORIENTATION_ROTATE_90:
        degree = 90;
        break;
      case ExifInterface.ORIENTATION_ROTATE_180:
        degree = 180;
        break;
      case ExifInterface.ORIENTATION_ROTATE_270:
        degree = 270;
        break;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return degree;
  }

  /**
   * rotate the bitmap
   * 
   * @param bitmap
   * @param degress
   * @return
   */
  public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
    if (bitmap != null) {
      Matrix m = new Matrix();
      m.postRotate(degress);
      bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
      return bitmap;
    }
    return bitmap;
  }
}

Related Tutorials