温馨提示×

android photopicker 如何进行图片压缩

小樊
81
2024-11-30 15:01:48
栏目: 编程语言

在Android中,使用PhotoPicker选择图片后,可以通过以下步骤对图片进行压缩:

  1. 首先,确保已经在项目中添加了Glide和BitmapFactory库的依赖。在app的build.gradle文件中添加以下代码:
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'
}
  1. 创建一个名为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;
    }
}
  1. 在选择图片后,调用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方法之前已经获得了所需的权限。

0