对Bitmap进行缩放后可以让其变小,对于网络传输有很大的帮助。另外在canvas上绘制Bitmap时使用的是Bitmap的原宽高,有时会出现过大或者过小的情况,通过比例缩放就能解决这一问题了。
实现的代码如下:
public Bitmap imageCompress(Bitmap oldBitmap) {
Bitmap newBitmap = oldBitmap;
int width = oldBitmap.getWidth();//读取旧图的宽度
int height = oldBitmap.getHeight();//读取旧图的高度
float scaleWidth;//缩放宽度
float scaleHeight;//缩放高度
int number = 100;//缩放比例,原图的百分比
Matrix matrix = new Matrix();
int newWidth = width;//新图的宽度,初始取原图
int newHeight = height;//新图的高度,初始取原图
while (newWidth > 1080 || newHeight > 1920) {
scaleWidth = (float) ((number * width * 0.01) / width);//按百分比进行缩放
scaleHeight = (float) ((number * height * 0.01) / height);//同上
matrix.postScale(scaleWidth, scaleHeight);
newBitmap = Bitmap.createBitmap(oldBitmap, 0, 0, width, height, matrix, true);//根据缩放比例获取新图
newWidth = newBitmap.getWidth();//获取新图的宽度
newHeight = newBitmap.getHeight();//获取新图的高度
number -= 10;//缩放比例减小
}
Log.i("bitMap", "图片比例:" + newHeight + "x" + newWidth);
return newBitmap;
}
对于上面的代码,每次缩放都是按照原图的宽和高进行缩放的,而不是根据生成的新图进行缩放。这是为了保持图片能按照原宽高比进行缩放,如果使用新图的宽高进行缩放就会出现裁剪的效果。