质量压缩:
public static void qualityCompress(Bitmap bitmap,File file){
int quality = 100;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,quality,bos);
while (bos.toByteArray().length/1024>1024){
bos.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG,quality-=10,bos);
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(bos.toByteArray());
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
通过bitmap的compress方法对bitmap进行质量压缩。图片的大小是没有变的,因为质量压缩不会减少图片的像素,它是在保持像素的前提下改变图片的位深及透明度等,来达到压缩图片的目的,这也是为什么该方法叫质量压缩方法。图片的长,宽,像素都不变,那么bitmap所占内存大小是不会变的。quality值越小压缩后的baos越小(使用场景:在微信分享时,或者图片传送时,需要对图片的字节数组大小进行限制,这时可以使用bitmap的compress方法对图片进行质量压缩)。
采样率压缩:
public static Bitmap inSampleCompress(File file,int width,int height){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(),options);
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize = Math.max(options.outWidth/600,options.outHeight/800);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
return bitmap;
}
当inJustDecodeBounds设置为true的时候,BitmapFactory通过decodeXXXX解码图片,将会返回空(null)的Bitmap对象,这样可以避免Bitmap的内存分配,但是它可以返回Bitmap的宽度、高度。
inSampleSize: 当它小于1的时候,将会被当做1处理,如果大于1,那么就会按照比例(1 / inSampleSize)缩小bitmap的宽和高、降低分辨率,大于1时这个值将会被处置为2的倍数。例如,width=100,height=100,inSampleSize=2,那么就会将bitmap处理为,width=50,height=50,宽高降为1 / 2,像素数降为1 / 4。