欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-20 14:10:22
从网上收集后自己写的一个方法; 1.首先是一个根据分辨率压缩的类,首先对图片进行一次压缩 /** * 根据分辨率压缩图片比例 * * @p...

从网上收集后自己写的一个方法;

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;
  }

 }

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

3.最后

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

下载地址:commonutils_jb51.rar

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

上一篇:

下一篇: