以前也没写怎么博客,写的不好,大家见谅!做Android开发也好几年了,总觉的该留下些什么,因为文笔有限,但也会把开发些最常用的东西很直观的分享给大家
废话不多了,以下是一些关图片的总结
一、须知
1、加载本地图片放在不同drawable下会影响生成bitmap宽高,从而影响大小
2、采用质量压缩法不会改变bitmap的大小(压缩的是手机存储file大小(100-0)值越小清晰度越低)
二、常见的几种压缩方式
1、质量压缩
(1)原理:保持像素的前提下改变图片的位深及透明度,(即:通过算法抠掉(同化)了图片中的一些某个些点附近相近的像素),达到降低质量压缩文件大小的目的。
(2)使用场景:将图片压缩后将图片上传到服务器,或者保存到本地。
(3)源码示例
public static Bitmap compressByQuality(final Bitmap src,
@IntRange(from = 0, to = 100) final int quality,
final boolean recycle) {
if (isEmptyBitmap(src)) return null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
src.compress(CompressFormat.JPEG, quality, baos);
byte[] bytes = baos.toByteArray();
if (recycle && !src.isRecycled()) src.recycle();
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
2、采样率压缩
(1)原理:设置图片的采样率,降低图片像素
(2) 好处:是不会先将大图片读入内存,大大减少了内存的使用,也不必考虑将大图片读入内存后的释放事宜。
(3)源码示例
public static Bitmap getBitmap(final String filePath, final int maxWidth, final int maxHeight) {
if (isSpace(filePath)) return null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
private static int calculateInSampleSize(final BitmapFactory.Options options,
final int maxWidth,
final int maxHeight) {
int height = options.outHeight;
int width = options.outWidth;
int inSampleSize = 1;
while ((width >>= 1) >= maxWidth && (height >>= 1) >= maxHeight) {
inSampleSize <<= 1;
}
return inSampleSize;
}
3、缩放法压缩(Matrix)
(1)原理:通过构建缩放矩阵和Bitmap.createBitmap方法来实现灵活缩放
(2)缩略图
(3)源码示例
public static Bitmap scale(final Bitmap src,
final float scaleWidth,
final float scaleHeight,
final boolean recycle) {
if (isEmptyBitmap(src)) return null;
Matrix matrix = new Matrix();
matrix.setScale(scaleWidth, scaleHeight);
Bitmap ret = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
if (recycle && !src.isRecycled()) src.recycle();
return ret;
}
(
4、createScaledBitmap(指定比例压缩)
1)原理,指定宽高生成新的位图
1)源码
public static Bitmap scale(final Bitmap src,
final int newWidth,
final int newHeight,
final boolean recycle) {
if (isEmptyBitmap(src)) return null;
Bitmap ret = Bitmap.createScaledBitmap(src, newWidth, newHeight, true);
if (recycle && !src.isRecycled()) src.recycle();
return ret;
}
(1)原理:去除透明度
5、RGB_565压缩(减少一半内存)
6、jni调用libjpeg库压缩
(1)原理:使用哈夫曼算法进行压缩
三、bitmap 所占内存
图片长度 x 图片宽度 x 一个像素点占用的字节数
例如一个1024x1024位深度为ARGB_8888 的bitmap,在手机占用的内存就是 1024x1024x4 = 4M
则改变其中任意一个数就能控制bitmap占用的大小
四、源码地址 :
https://download.youkuaiyun.com/download/u014227348/10612749