1.尺寸压缩:
就Android Bitmap面面观|杰风居 该链接的Bitmap详情说的很清晰,建议了解一下。 这篇文章说的,使用Bitmap节省内存最重要的技巧就是加载合适大小的缩略图,需要先读取Bitmap的原始大小并且设置inJustDecodeBounds ,按缩小了合适的倍数的大小Bitmap进行加载。
public static Bitmap decodeSampledBitmapByPath(String path, int reqWidth, int reqHeight) {
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
2.质量压缩
该定义转自详解Bitmap尺寸压缩与质量压缩|flowsky37——质量压缩不会改变图片的像素点,即前面我们说到的在转化为bitmap时占用内存变大时状况不会得到改善。但是能方便的设置压缩百分比,达到我们需要的大小。还是先看方法:
Bitmap.compress(CompressFormat format, int quality, OutputStream stream)
简单解释一下这三个参数,第一个表示Bitmap被压缩成的图片格式;第二个表示压缩的质量控制,范围0~100,很好理解。quality为80,表示压缩为原来80%的质量效果。有些格式,例如png,它是无损的,这个值设置了也是无效的。因为质量压缩是在保持像素前提下改变图片的位深及透明度等来压缩图片的。
public static Bitmap compressBitmap(Bitmap bitmap, int maxkb) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length / 1024 > maxkb && options > 0) {
baos.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 5;
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
bitmap = BitmapFactory.decodeStream(isBm, null, null);
LogUtil.e(TAG, options + "," + baos.toByteArray().length / 1024);
return bitmap;
}