在Android中,使用PhotoPicker选择图片后,可以通过以下步骤对图片进行压缩:
dependencies {
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
implementation 'androidx.bitmap:bitmap:1.0.0'
}
ImageCompressor
的工具类,用于压缩图片:import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageCompressor {
public static void compressImage(Context context, File imageFile, int maxWidth, int maxHeight, String outputPath) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
options.inJustDecodeBounds = false;
Bitmap scaledBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
FileOutputStream out = new FileOutputStream(outputPath);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private 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;
while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
ImageCompressor
类的compressImage
方法对图片进行压缩:File imageFile = ...; // 从PhotoPicker获取的图片文件
String outputPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/compressed_" + System.currentTimeMillis() + ".jpg";
ImageCompressor.compressImage(context, imageFile, 1000, 1000, outputPath);
注意:在Android 6.0(API级别23)及更高版本中,需要在运行时请求存储权限。确保在调用compressImage
方法之前已经获得了所需的权限。