Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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,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;
  }

 }

这个方法用来动态设置每次压缩的比例,主要用于提升压缩的时间,这其中的数值是我大概测试出来的可以修改成你认为比较合适的

3.最后

压缩图片费时又费内存,很明显执行的时候需要在子线程中完成,如果需要的话可以加一个压缩完成的监听

下载地址:CommonUtils_code.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

大佬总结

以上是大佬教程为你收集整理的android 将图片压缩到指定的大小的示例全部内容,希望文章能够帮你解决android 将图片压缩到指定的大小的示例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。