先看如下代码, 其中 options.inSampleSize 各类文章谬种流传,大肆宣扬,其实,这个参数Bitmap.CompressFormat.PNG下,对压缩比影响 较小,实测一张 小米5拍的4.7M 3456 * 4608的图片,即使 inSampleSize 的值达到3,图片大小也只是4.1M左右。真正厉害的是Bitmap.CompressFormat.JPEG ,这个在100的ration下能压倒1.3M左右,ration是最最关键的,60%就可以压倒几百k,如果是Bitmap.CompressFormat.PNG,则对原图大小没啥影响
public static byte[] compressPic(String path) {
//获得图片的宽和高,但并不把图片加载到内存当中
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int width = options.outWidth;
int height = options.outHeight;
int reqWidth = SpManager.getScreenWidth();
int reqHeight = SpManager.getScreenHeight();
if(width > reqWidth || height > reqHeight){
int widthRatio = Math.round(width * 1.0f / reqWidth);
int heightRatio = Math.round(height * 1.0f /reqHeight);
options.inSampleSize = Math.max(widthRatio, heightRatio);
}
//使用获取到的inSampleSize再次解析图片
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ration = 100;
if(options.inSampleSize > 5 ) {
ration = 40;
} else if(options.inSampleSize > 1 ) {
ration = 60;
}
bitmap.compress(Bitmap.CompressFormat.JPEG, ration, baos);
return baos.toByteArray();
}