DuKBitmapImages 图片压缩处理技术

来源:互联网 发布:如何代理淘宝网店 编辑:程序博客网 时间:2024/06/06 23:53

Android图片压缩上传系列

*压缩中的问题:

--图片压缩上如果存在问题,势必造成消耗大量的流量,下载图片的速度慢等影响产品性能,那么如何解决?请看下面:

  1. 压缩图片一共多少张?一起压缩?分开压缩?尺寸?
  2. 压缩后的图片保存的路径?
  3. 对于多图压缩性能处理的问题?并发or线性处理?
  4. 能不能使用service来进行压缩处理,是local(本地)还是remote(远程)的方式来启动service?
  5. 如果需要压缩的图片非常多,如何使用线程池来处理?
 

 其实做过图片压缩的朋友应该知道,这一块的技术点就那么几个,按照逻辑处理起来也是不一样的效果,主要是关注处理出来的图片的尺寸和质量。

* 等比压缩

这里首先按照原始图片的宽高比,等比计算出sampleSize。代码网上也有相关,这里贴出方法的代码:

BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeFile(srcImagePath, options);//根据原始图片的宽高比和期望的输出图片的宽高比计算最终输出的图片的宽和高float srcWidth = options.outWidth;float srcHeight = options.outHeight;float maxWidth = outWidth;//期望输出的图片宽度float maxHeight = outHeight;//期望输出的图片高度float srcRatio = srcWidth / srcHeight;float outRatio = maxWidth / maxHeight;float actualOutWidth = srcWidth;//最终输出的图片宽度float actualOutHeight = srcHeight;//最终输出的图片高度if (srcWidth > maxWidth || srcHeight > maxHeight) {    if (srcRatio < outRatio) {        actualOutHeight = maxHeight;        actualOutWidth = actualOutHeight * srcRatio;    } else if (srcRatio > outRatio) {        actualOutWidth = maxWidth;        actualOutHeight = actualOutWidth / srcRatio;    } else {        actualOutWidth = maxWidth;        actualOutHeight = maxHeight;    }}//计算sampleSizeoptions.inSampleSize = computSampleSize(options, actualOutWidth, actualOutHeight);

 

 *图片质量压缩

ANDORID API:

public boolean compress(CompressFormat format, int quality, OutputStream stream)

方法如下:

//进行有损压缩ByteArrayOutputStream baos = new ByteArrayOutputStream();int options_ = 100;actualOutBitmap.compress(Bitmap.CompressFormat.JPEG, options_, baos);//质量压缩方法,把压缩后的数据存放到baos中 (100表示不压缩,0表示压缩到最小)int baosLength = baos.toByteArray().length;while (baosLength / 1024 > maxFileSize) {//循环判断如果压缩后图片是否大于maxMemmorrySize,大于继续压缩    baos.reset();//重置baos即让下一次的写入覆盖之前的内容    options_ = Math.max(0, options_ - 10);//图片质量每次减少10    actualOutBitmap.compress(Bitmap.CompressFormat.JPEG, options_, baos);//将压缩后的图片保存到baos中    baosLength = baos.toByteArray().length;    if (options_ == 0)//如果图片的质量已降到最低则,不再进行压缩        break;}

那么有个耗时问题,这里的开个线程去处理这件事。

为了达到最佳的压缩结果,可以将上面两种方案同时进行。如果压缩消耗的时间很长,需要将压缩过程放入后台线程中执行。

这里实现的功能有:

  1. 打开摄像头进行拍照处理(旋转、截取)
  2. 处理后的图片保存到指定位置
  3. 压缩后的照片保存到指定目录下
  4. 使用AsyncTask执行压缩操作,处理耗时问题
  5. 显示压缩后的照片及其相关信息到前台activity


另外,如何结合使用service和多线程会在下篇文章具体说明。

开源github地址如下:
DuKBitmapImages


欢迎大家访问并star,如果有任何问题可以在评论中加以提问,谢谢~~



 


0 0
原创粉丝点击