android 将图片压缩到指定的大小的示例

1.首先是一个根据分辨率压缩的类,首先对图片进行一次压缩

/**
  * 根据分辨率压缩图片比例
  *
  * @param imgPath
  * @param w
  * @param h
  * @return
  */
 private static Bitmap compressByResolution(String imgPath, int w, int h) {
  BitmapFactory.Options opts = new BitmapFactory.Options();
  opts.inJustDecodeBounds = true;
  BitmapFactory.decodeFile(imgPath, opts);

  int width = opts.outWidth;
  int height = opts.outHeight;
  int widthScale = width / w;
  int heightScale = height / h;

  int scale;
  if (widthScale < heightScale) { //保留压缩比例小的
   scale = widthScale;
  } else {
   scale = heightScale;
  }

  if (scale < 1) {
   scale = 1;
  }
  Log.i(TAG,"图片分辨率压缩比例:" + scale);

  opts.inSampleSize = scale;

  opts.inJustDecodeBounds = false;

  Bitmap bitmap = BitmapFactory.decodeFile(imgPath, opts);

  return bitmap;
 }
2.第二就是循环对图片的压缩,直到压缩到指定的大小以下为止(重要!)

 /**
  * 根据分辨率压缩
  *
  * @param srcPath 图片路径
  * @param ImageSize 图片大小 单位kb
  * @return
  */
 public static boolean compressBitmap(String srcPath, int ImageSize, String savePath) {
  int subtract;
  Log.i(TAG, "图片处理开始..");
  Bitmap bitmap = compressByResolution(srcPath, 1024, 720); //分辨率压缩
  if (bitmap == null) {
   Log.i(TAG, "bitmap 为空");
   return false;
  }
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  int options = 100;
  bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
  Log.i(TAG, "图片分辨率压缩后:" + baos.toByteArray().length / 1024 + "KB");


  while (baos.toByteArray().length > ImageSize * 1024) { //循环判断如果压缩后图片是否大于ImageSize kb,大于继续压缩
   subtract = setSubstractSize(baos.toByteArray().length / 1024);
   baos.reset();//重置baos即清空baos
   options -= subtract;//每次都减少10
   bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
   Log.i(TAG, "图片压缩后:" + baos.toByteArray().length / 1024 + "KB");
  }
  Log.i(TAG, "图片处理完成!" + baos.toByteArray().length / 1024 + "KB");
  try {
   FileOutputStream fos = new FileOutputStream(new File(savePath));//将压缩后的图片保存的本地上指定路径中
   fos.write(baos.toByteArray());
   fos.flush();
   fos.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

  if (bitmap != null) {
   bitmap.recycle();
  }

  return true; //压缩成功返回ture
 }
/**
  * 根据图片的大小设置压缩的比例,提高速度
  *
  * @param imageMB
  * @return
  */
 private static int setSubstractSize(int imageMB) {

  if (imageMB > 1000) {
   return 60;
  } else if (imageMB > 750) {
   return 40;
  } else if (imageMB > 500) {
   return 20;
  } else {
   return 10;
  }

 }


原文地址:http://www.jb51.net/article/105746.htm



猜你喜欢

转载自blog.csdn.net/u012716909/article/details/78591510