如何获取图库图像的压缩图像uri?

问题描述 投票:0回答:1

我正在一个需要压缩图像并且需要为该压缩图像获取Uri的项目中工作。问题是,当我尝试从图库中压缩图像时,它正在创建另一个图像,该图像与原始图像以不同的分辨率一起压缩,如何实现,就像我在图库中只应有一个图像参考,这也是原始图像而不是压缩图像。请在下面找到我尝试过的代码片段

    public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {

    int width = image.getWidth();
    int height = image.getHeight();

    float bitmapRatio = (float) width / (float) height;
    if (bitmapRatio > 1) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }

    return Bitmap.createScaledBitmap(image, width, height, true);

}

private static Bitmap rotateImage(Bitmap img, float degree) {
    Matrix matrix = new Matrix();
    matrix.postRotate(degree);
    Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
    //img.recycle();
    return rotatedImg;
}

private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {

    InputStream input = context.getContentResolver().openInputStream(selectedImage);
    ExifInterface ei;
    if (Build.VERSION.SDK_INT > 23)
        ei = new ExifInterface(input);
    else
        ei = new ExifInterface(selectedImage.getPath());

    int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            return rotateImage(img, 90);
        case ExifInterface.ORIENTATION_ROTATE_180:
            return rotateImage(img, 180);
        case ExifInterface.ORIENTATION_ROTATE_270:
            return rotateImage(img, 270);
        default:
            return img;
    }
}

public static Uri compressedImageUri(Uri selectedImage, Context context) {
    try {

        InputStream imageStream = null;
        try {
            imageStream = context.getContentResolver().openInputStream(
                    selectedImage);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap original = BitmapFactory.decodeStream(imageStream);
        //Bitmap bmp = getResizedBitmap(original, 500);
        Bitmap rotateBitmap = rotateImageIfRequired(context, original, selectedImage);
        Bitmap bmp = getResizedBitmap(rotateBitmap, 500);
        String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, String.valueOf(System.currentTimeMillis()), null);

        return Uri.parse(path);
    } catch (Exception e) {
        Log.d("error", e.getLocalizedMessage());
    }
    return null;

}
android bitmap android-gallery image-compression
1个回答
2
投票

使用此Compressor.class

Compressor.class

您可能需要其他班级,所以请检查File imgFile = new File(uri.getPath()); File compressFile = Compressor.getDefault(getContext()).compressToFile(imgFile); 包装。希望这会对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.