使用bitmap.compress(Bitmap.CompressFormat.PNG, 0, fOut)压缩图片会使图片大小比原始大小更大

19

我想将从相机拍摄的图片压缩成PNG格式,以使它们更小,因此我正在使用以下代码:

compressedPictureFile = new File(imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
FileOutputStream fOut = new FileOutputStream(compressedPictureFile);
boolean compressed = bitmap.compress(Bitmap.CompressFormat.PNG, 0, fOut);
fOut.flush();
fOut.close();

问题在于压缩后的图片文件实际上比原始图片还要大(从1MB增加到了6MB)。

我错过了什么?这是否是减小图像大小的最佳方法?

谢谢

2个回答

29

使用相机拍摄的图片很可能以jpg格式存储,这是有损压缩,但对于颜色丰富的图像(例如照片)而言相对较好。

使用您的方法压缩位图时,保存为png。png压缩是无损的,但在颜色较少的情况下(例如特定商标或其他图形),可以实现相当小的文件大小。当png文件中的颜色和复杂性增加时,文件大小也会增加(这就是相机保存jpg的原因-大多数照片的质量/文件大小比率要比png好得多)。

因此,如果要减小照片的文件大小,请使用jpg压缩,并尝试使用质量参数进行实验。您还可以降低图像的分辨率,因为这将节省大量空间(50%分辨率的文件大小约为25%)。


质量参数和分辨率是一样的吗?我该如何降低分辨率? - Dany Y
1
quality参数会影响使用jpg压缩时颜色的保留程度,但在输出png时没有任何影响。您可以在此处阅读有关compress方法的一些信息:http://developer.android.com/reference/android/graphics/Bitmap.html#compress%28android.graphics.Bitmap.CompressFormat,%20int,%20java.io.OutputStream%29 - Jave
1
有很多关于减小图像大小的教程,但最简单的方法是通过Bitmap.createScaledBitmap创建一个新的、较小的位图:http://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap%28android.graphics.Bitmap,%20int,%20int,%20boolean%29 - Jave
如果您使用PNG格式,则不会压缩图像,因为PNG是无损格式。请使用JPEG来压缩您的图像。 - Adeel
@Adeel,PNG使用无损压缩 - Jave
@Java 亲爱的,我在上面的评论中提到了同样的事情 :) - Adeel

0

我的应用程序上它运行得很好

    public static String makeScreen(View view) throws Exception {
    String filename = "file.png";
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap b = view.getDrawingCache();
    FileOutputStream file = null;

    try {
        file = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "folder/" + filename);
        if (file != null) {
            b.compress(Bitmap.CompressFormat.PNG, 98, file);
            file.close();
        }
        view.destroyDrawingCache();
    } catch (Exception e) { view.destroyDrawingCache(); }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接