Android图片压缩
时间: 2023-10-25 21:33:21 浏览: 46
在 Android 中进行图片压缩可以使用以下两种方式:
1. 使用 BitmapFactory 进行图片压缩
```java
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// 首先将 inJustDecodeBounds 设置为 true,解析图片的宽高信息,不将图片的像素加载到内存中
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 根据计算出的 inSampleSize 来进行图片的压缩
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 将 inJustDecodeBounds 设置为 false,重新解析图片,这次会将图片的像素加载到内存中
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// 获取图片的原始宽高
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
// 如果图片的宽高比目标宽高大,则进行压缩
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// 计算 inSampleSize 的值,确保宽高都不会超过目标宽高
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
```
调用该方法时,可以指定需要压缩到的目标宽高:
```java
Bitmap compressedBitmap = decodeSampledBitmapFromResource(getResources(), R.drawable.image, 500, 500);
```
2. 使用第三方库进行图片压缩
在 Android 中有很多第三方库可以用来进行图片压缩,比如:
- Luban:https://github.com/Curzibn/Luban
- Compressor:https://github.com/zetbaitsu/Compressor
这些库通常都提供了简单易用的 API,可以很方便地进行图片压缩。