在上一篇文章中(Android之图片变换)主要说明了bitmap的使用,当然其中也包括一点图片压缩的内容,但是没有详细描述,这篇文章就来阐述一下平时Android使用的图片压缩技术

从图片的压缩方式区分:质量压缩和尺寸压缩。

质量压缩是在保持像素的前提下改变图片的位深及透明度等,来达到压缩图片的目的,经过它压缩的图片文件大小会有改变,但是导入成bitmap后占得内存是不变的。因为要保持像素不变,所以它就无法无限压缩,到达一个值之后就不会继续变小了。显然这个方法并不适用与缩略图,其实也不适用于想通过压缩图片减少内存的适用,仅仅适用于想在保证图片质量的同时减少文件大小的情况而已

尺寸压缩是压缩图片的像素,一张图片所占内存的大小 图片类型*宽*高,通过改变三个值减小图片所占的内存,防止OOM,当然这种方式可能会使图片失真

质量压缩:

public Bitmap compressImage(Bitmap image,int imageSize) {   ByteArrayOutputStream baos = new ByteArrayOutputStream();   image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中    int options = 100;    while ( baos.toByteArray().length / 1024>imageSize) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩           baos.reset();//重置baos即清空baos           image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中           options -= 10;//每次都减少10    }    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片    return bitmap;  } 

尺寸压缩:

public void scalePic(int reqWidth,int reqHeight) {   BitmapFactory.Options options = new BitmapFactory.Options();   options.inJustDecodeBounds = true;   BitmapFactory.decodeResource(getResources(), R.mipmap.demo, options);   options.inSampleSize = PhotoUtil.calculateInSampleSize(options, reqWidth,reqHeight);   options.inJustDecodeBounds = false;   bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.demo, options);   postInvalidate(); }
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {   final int height = options.outHeight;   final int width = options.outWidth;   int inSampleSize = 1;   if (height > reqHeight || width > reqWidth) {         final int heightRatio = Math.round((float) height / (float) reqHeight);         final int widthRatio = Math.round((float) width / (float) reqWidth);        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;    }   return inSampleSize; }

根据具体需求也可以两种压缩方式结合使用

更多相关文章

  1. Android(安卓):为你的启动页面SplashActivity 添加动画的几种方法
  2. android屏幕横向滚动,android图片横向滚动
  3. Android加载大图片时的OOM异常及解决(图片的二次采样)
  4. Android之解决全屏切换非全屏的页面压缩问题
  5. 前沿技术:FaceBook推出的Android图片加载库Fresco
  6. Android(安卓)UI设计小知识——富文本
  7. android 应用opencv 对图片的处理
  8. android中,由于图像处理不当而引起的OOM问题及其解决方案(一)
  9. 三种方法,刷新 Android(安卓)的 MediaStore!让你保存的图片立即出

随机推荐

  1. 初学Android,数据存储之使用SQLite数据库
  2. 【Android高级】Android系统以及Activity
  3. 关于Android这个名字。。。
  4. 为Android(和其他移动平台)安装MoSync
  5. android热更新
  6. Android(安卓)View 绘制刷新流程分析
  7. android (java) 网络发送get/post请求参
  8. Android SDK 2.2 开发环境详解
  9. Android(安卓)Webview组件使用总结
  10. Android JNI开发入门之二(javah命令的补