android - Bitmap.compress 不会减少字节数

标签 android bitmap compression image-compression

我需要压缩图像以将其发送到我的服务器。我正在尝试这样做:

private Bitmap compressImage(Bitmap bitmapImg){
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bitmapImg.compress(Bitmap.CompressFormat.JPEG, 50, out);
    Bitmap compressed = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

    return compressed;
}

但是当我比较原始位图对象和压缩后的位图对象的字节数时,我得到相同的数字:

Log.e("UNCOMPRESSED", Integer.toString(mBitmapImg.getByteCount()));
E/UNCOMPRESSED: 23970816
Log.e("COMPRESSED", Integer.toString(compressedBitmapImg.getByteCount()));
E/COMPRESSED: 23970816

我怎样才能解决这个问题以获得更小的文件?

最佳答案

But when I compare the Byte count of the original Bitmap object and the compressed one, I get the same number:

Bitmap 的大小在内存中基于其分辨率(以像素为单位的宽度和高度)和位深度(每个像素的字节数,用于控制每个像素可以使用多少种颜色)。

How can I fix this to have a smaller file?

您没有文件。你有一个 Bitmap内存中的对象。图像文件通常以压缩形式存储。尤其是 JPEG、PNG、WebP 和 GIF 这四种在 Android 中使用的主要图像格式。因此,例如 out.toByteArray()将小于 23,970,816 字节。

此外,您没有发送 Bitmap到服务器。您正在向服务器发送图像。您需要阅读服务器的文档,或与服务器开发人员交谈,以确定他们支持的图像格式以及如何将图像发送到服务器(理想情况下,像 HTTP PUT 这样高效的东西)。

如果你想减少 Bitmap 的内存大小,将其缩放为较低分辨率的图像(例如,通过 createScaledBitmap() )。

关于android - Bitmap.compress 不会减少字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44890833/

相关文章:

java - 小部件没有被转换。我如何解决它?

Android - 如何加载大图像(将其转换为较小的尺寸)并将其作为 Base64 字节数组发送(避免 OutOfMemory 错误)

c# - 如何将 Android.Graphics 的 GetPixel 给出的 Int 转换为 Color?

位图克隆上的 C# WinForms 内存不足异常

java - Android - 在一部手机上压缩位图非常慢,在另一部手机上很快

Java Android - 动态加载 fragment (ViewPager)

Android:android.view.ViewRoot$CalledFromWrongThreadException - 如何解决这个问题?

android - 单击项目时从 ListActivity 返回到上一个 Activity

c++ - 在 C++ 中减小大小/压缩 JSON 字符串

java - GZIP 输出流 : Increase compression level