这里记录下Android三种常见的图片压缩方法:质量压缩,尺寸压缩和采样率压缩
质量压缩
采用系统自带的质量压缩算法,将图片压缩成JPEG格式
public static Bitmap compressQuality(Bitmap bitmap, int quality) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return BitmapFactory.decodeStream(bais, null, null);//把ByteArrayInputStream数据生成图片
}
尺寸压缩
根据图片的缩放比例进行等比大小的缩小尺寸
public static Bitmap compressSize(Bitmap bitmap) {
int ratio = 8;//尺寸压缩比例
Bitmap result = Bitmap.createBitmap(bitmap.getWidth() / ratio, bitmap.getHeight() / ratio, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Rect rect = new Rect(0, 0, bitmap.getWidth() / ratio, bitmap.getHeight() / ratio);
canvas.drawBitmap(bitmap, null, rect, null);
return compressQuality(result, 100);
}
最后调用了质量压缩的方法compressQuality
采样率压缩
根据图片的采样率大小进行压缩
public static Bitmap compressSample(String filePath) {
int inSampleSize = 8;//采样率设置
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = inSampleSize;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
return compressQuality(bitmap, 100);
}
最后调用了质量压缩的方法compressQuality