在android应用开发中会出现很多需要实现图片缩放的地方,或者是出于美观,或者是出于节省内存。。
在这里博主总结了几种比较常用的图片缩放的方法
第一种:通过 BitmapFactory.Options
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picpathString, opts); //只把图片的边界信息加载到内存,节省内存
Log.i(TAG, "opts.outHeight=======>" + opts.outHeight);
Log.i(TAG, "opts.outWidth=====>" + opts.outWidth);
if (opts.outHeight != 0 && opts.outWidth != 0)
{
opts.inSampleSize = (int) ((opts.outWidth * 5) / width); //inSampleSize这个参数是压缩的倍数,具体可以自己调节,必须是int
Log.i(TAG, "opt.inSampleSize---->" + opts.inSampleSize);
}
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(picpathString, opts); //此时得到的bitmap就是压缩后的bitmap了
第二种:通过 matrix
// 获取这个图片的宽度和高度
int width = _cameraImage.getWidth();
int hegith = _cameraImage.getHeight();
// 创建操作图片用的Matrix对象
Matrix matrix = new Matrix();
int degree = 90;
Log.i(TAG, "degree--->" + degree);
// 旋转图片
matrix.postRotate(degree);
matrix.postScale(NewscaleWidth, NewscaleHeight);//缩放图片
// 创建新的图片
Bitmap resizedBitmap = null;
resizedBitmap = Bitmap.createBitmap(_cameraImage, 0, 0, width, hegith, matrix, true);
第三种:通过canvas对bitmap重绘得到缩放图
Rect r = bitmap.getCropRect();//这个方法要自己写得到原bitmap所占的矩形区域
int width = r.width(); // CR: final == happy panda!
int height = r.height();
Bitmap newbitmap = null;
newbitmap= Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);{
Canvas canvas = new Canvas(newbitmap);
Rect dstRect = new Rect(0, 0, new_width, new_height); //要把原图缩放到多大的矩形区域
Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawBitmap(newbitmap, r, dstRect, paint); //缩放成功
}
第四种方法:ThumbnailUtils
Bitmap newbitmap = null;
newbitmap = ThumbnailUtils.extractThumbnail(imageAfterCroped, maxWeight, maxHeight,
OPTIONS_RECYCLE_INPUT);
这是我总结的集中简单的处理图片的方法,欢迎交流,转载请注明出处。谢谢。