减少Android中的图像文件大小(图像类型未知)



我想让用户选择他们想将图像文件大小减少多少,可以是低、中或高,然后将图像上传到服务器。这部分很容易。

下一部分是文件大小的实际缩减。我正在获取图像URI,我想减小文件图像文件的大小,图像类型可以是png、jpg或其他类型。

我知道Bitmap.compress(),这是实现的唯一方法吗?还是有一个现有的开源库?

Bitmap bitmap;
bitmap = MyBitmapFactory.decodeFile(PATHTOPICT, UPLOAD_REQUIRED_SIZE);
if (bitmap != null) {
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

使用方法(在谷歌上找到):

public static Bitmap decodeFile(String filePath, final int REQUIRED_SIZE) {
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp <= REQUIRED_SIZE && height_tmp <= REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}

如果某个值为NULL,则表示它没有图像/建议按幂缩放2!!!

最新更新