压缩图片实例

来源:互联网 发布:笔记本性能测试软件 编辑:程序博客网 时间:2024/05/01 16:18

实例如下,

package com.test.testactivity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.util.Log;public class CompressBMP {private static final String TAG = "CompressBMP";public static Bitmap decodeSampledBitmapFromResource(String path,        int reqWidth, int reqHeight) {// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeFile(path, options);    // 调用上面定义的方法计算inSampleSize值    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);    // 使用获取到的inSampleSize值再次解析图片    options.inJustDecodeBounds = false;    return BitmapFactory.decodeFile(path, options);}public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {// 源图片的高度和宽度final int height = options.outHeight;final int width = options.outWidth;Log.d(TAG, "原图大小为:"+height+"*"+width);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的值,这样可以保证最终图片的宽和高// 一定都会大于等于目标的宽和高。inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}return inSampleSize;}}

然后在acticity中有如下代码:

Button btn_setview = (Button) this.findViewById(R.id.btn_setview);final ImageView imageview = (ImageView) this.findViewById(R.id.imageview);btn_setview.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubBitmap bitmap = CompressBMP.decodeSampledBitmapFromResource(APP_ROOT_DIR, 100, 100);Log.d(TAG, "原图压缩之后的大小为:"+bitmap.getHeight()+"*"+bitmap.getWidth());imageview.setImageBitmap(bitmap);}});

运行之后打印如下log:

原图大小为:768*1024原图压缩之后的大小为:96*128

1024/100 > 768/100,所以选择768/100作为压缩的比例,四舍五入为8,1024/8=128,768/8=96.

0 0
原创粉丝点击