有时候业务需要,需要对图片进行压缩处理,在这里介绍一种按比例压缩图片的方法,不多说,大家直接看代码吧
/**
* 按比例压缩图片
* @param picture
* @return
*/
public static Bitmap compressAvatar(byte[] picture){
//加载图片的边界信息(只读取图片的高度,宽度,不读取字节)
BitmapFactory.Options options = new BitmapFactory.Options();
//将此选项设置为true,再加载图片。就会只读取图片边界信息
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(picture, 0, picture.length, options);
//计算压缩比例
options.inSampleSize=calculateInSampleSize(options,20,20);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length, options);
return bitmap;
}
/**
* 计算压缩比例
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
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) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;//高度和宽度都按此比例进行压缩
}
本文介绍了一种按比例压缩图片的技术实现方法,并提供了具体的代码示例。该方法首先读取图片尺寸信息,然后计算合适的压缩比例,最后按此比例压缩图片。
2994

被折叠的 条评论
为什么被折叠?



