android 图片压缩
来源:互联网 发布:centos编译c 编辑:程序博客网 时间:2024/06/10 03:02
图片压缩常用的两种方式:
- 质量压缩
- 按比例压缩
1、质量压缩
/** * 质量压缩 */ public static Bitmap compressImage(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); int options = 100; while (baos.toByteArray().length / 1024 > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();//清空baos options -= 10; bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); Bitmap compressBitmap = BitmapFactory.decodeStream(bais); return compressBitmap; }
按比例压缩
先要读取位图的尺寸与类型
BitmapFactory.Options options = new BitmapFactory.Options(); //在解码的时候,避免内存的分配,即它会返回一个null的Bitmap对象 //但是可以获取它的尺寸与类型,outWidth,outHeight与outMineType options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.drawable.picture,options); int imageWidth = options.outWidth; int imageHeight = options.outHeight; String imageType = options.outMimeType;
计算inSampleSize的值
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 halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; }
获取压缩后的图片
public static Bitmap decodeSampleBitmapFromResource( Resources res, int resId, int reqWidth, int reqHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqWidth); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); }
最后直接可以显示了
mImg.setImageBitmap( decodeSampledBitmapFromResource(getResources(), R.id.picture, 100, 100));
0 0
- android图片压缩方法
- android图片压缩方法
- android图片压缩
- android图片压缩
- Android图片压缩
- android图片压缩
- Android BitmapFactory 图片压缩
- android图片压缩
- android图片压缩总结
- android图片压缩一:
- Android 图片压缩二:
- Android图片压缩总结
- Android开发压缩图片
- Android图片压缩
- android 的图片压缩
- Android关于图片压缩
- android 图片压缩
- android图片压缩上传
- S3C2451_lcd屏显示操作详解代码_ARM
- Unicode UTF的不同
- servlet链接数据库的过程中问题多多
- 比较器之几种电压比较器电路
- C++new与delete以及空指针
- android 图片压缩
- Android下拉刷新SwipeRefreshLayout控件的简单使用
- windows7 集成nginx 1.8.1(稳定版本)
- 广搜的简单应用1015
- 无线破解攻击工具Aircrack-ng使用详解
- Java的Socket编程
- SPOJ 7758 MGLAR10 - Growing Strings
- Docker生态系统一览
- 解惑 -- static