我在输入中有一个由相机返回的字节数组。
我需要缩小我的图像以使其大小等于 500KB。我正在尝试使用位图来实现这一点,但我找不到如何获得正确的compression
值。
public static byte[] compressCapture(byte[] capture) {
// How to get the right compression value ?
int compression = 50;
Bitmap bitmap = BitmapFactory.decodeByteArray(capture, 0, capture.length);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
return outputStream.toByteArray();
}
问题是压缩与图像大小不成正比,这意味着compression
等于 50 不会将图像大小除以 2。
有没有办法在不依赖于焦点或智能手机型号的输出中获得固定的图像尺寸?
编辑 :
我不想使用文件(我使用机密数据)。
更新 01/16/2018
最简单的方法是使用BitmapFactory.Options.inSampleSize
解码字节数组并同时压缩它。这是文档
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // If you want an image four times smaller than the original
Bitmap decoded = BitmapFactory.decodeByteArray(data, 0, data.length, options);
旧答案,请不要使用这个
由于显然无法一次性实现这一目标,因此我实施了一个迭代过程以达到以 KB 为单位的给定大小。
我从等于 80 的压缩系数开始,如果还不够,我会降低这个系数,然后重试,直到大小低于我的阈值。
static COMPRESSION_PERCENTAGE_START = 80;
static IMAGE_COMPRESSION_EXPECTED_MAX_ITERATIONS = 3;
static IMAGE_COMPRESSION_STEP_PERCENT = 5;
// For logging
static IMAGE_COMPRESSION_EXPECTED_MAX_ITERATIONS = 5;
static byte[] compressCapture(byte[] capture, int maxSizeKB) {
long maxSizeByte = ((long) maxSizeKB) * 1_000;
if (capture.length <= maxSizeByte) return capture;
byte[] compressed = capture;
// Chosen arbitrarily so that we can compress multiple times to reach the expected size.
int compression = COMPRESSION_PERCENTAGE_START;
Bitmap bitmap = BitmapFactory.decodeByteArray(capture, 0, capture.length);
ByteArrayOutputStream outputStream;
int iterations = 0;
while (compressed.length > maxSizeByte) {
// Just a counter
iterations++;
compression -= IMAGE_COMPRESSION_STEP_PERCENT;
outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
compressed = outputStream.toByteArray();
}
if (iterations > IMAGE_COMPRESSION_EXPECTED_MAX_ITERATIONS) {
Timber.w("Compression process has iterated more than expected, with " + iterations + " iterations.");
}
return compressed;
}
这是原始大小1_871_058字节的输出大小
它为我完成了这项工作,但如果您使用它请小心,它当然需要一些微调,我只是在给定的智能手机型号上对其进行了测试。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句