【问题标题】:bitmap.compress(Bitmap.CompressFormat.PNG, 0, fOut) making image size bigger than originalbitmap.compress(Bitmap.CompressFormat.PNG, 0, fOut) 使图像尺寸大于原始尺寸
【发布时间】:2013-04-17 03:08:02
【问题描述】:

我想将相机拍摄的图像压缩为 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();

问题是compressedPictureFile实际上比原始图像大(从1 Mb到6Mb)

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

谢谢

【问题讨论】:

    标签: android compression image-resizing bitmapfactory


    【解决方案1】:

    使用相机拍摄的图像很可能以jpg 格式存储,这种格式是有损的,但对于具有大量颜色的图像(例如照片)相对较好。

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

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

    【讨论】:

    • 质量参数和分辨率一样吗?如何降低分辨率?
    • quality-参数会影响使用 jpg 压缩时颜色的保存程度。输出 png 时没有任何效果。你可以在这里阅读一些关于compress-方法的信息:developer.android.com/reference/android/graphics/…
    • 有很多关于减小图像尺寸的教程,但最简单的方法是通过Bitmap.createScaledBitmap 创建一个新的、更小的位图:developer.android.com/reference/android/graphics/…
    • 如果您使用的是 PNG 格式,则它不会压缩您的图像,因为 PNG 是一种无损格式。使用 JPEG 压缩图像
    • @Adeel,PNG 使用 lossless compression
    【解决方案2】:

    它在我的应用上运行良好

        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(); }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多