【问题标题】:Reduce image file size in Android (image type unknown)减小 Android 中的图像文件大小(图像类型未知)
【发布时间】:2013-08-04 00:32:18
【问题描述】:

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

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

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

【问题讨论】:

    标签: android image-processing compression


    【解决方案1】:
    Bitmap bitmap;
    bitmap = MyBitmapFactory.decodeFile(PATHTOPICT, UPLOAD_REQUIRED_SIZE);
    if (bitmap != null) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    

    用方法(用google找到):

    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 缩放!!!

    【讨论】:

    • 您的解决方案仅适用于 JPEG?你能解释一下PNG和BMP吗?
    • 如何将结尾从 *.jpg 编辑为 *.whatyouwant 或尝试 Bitmap.CompressFormat.PNG
    最近更新 更多