有没有办法将位图压缩到特定的字节大小?例如,1.5MB。问题是到目前为止我看到的所有示例都是调整宽度和高度的大小,但我的要求是调整字节大小。那可能吗? 另外,压缩Bitmap最直接正确的方法是什么?我对这个话题还很陌生,希望从一开始就朝着正确的方向前进。
最佳答案
这是我创建的一个辅助类。这将按宽度/高度然后按最大文件大小压缩位图。将图像缩小到 1.5mb 并不是一门精确的科学,但它的作用是,如果图像大于要求,它会使用 jpeg 压缩位图并将质量降低 80%。一旦文件大小小于所需大小,它就会以字节数组的形式返回位图。
public static byte[] getCompressedBitmapData(Bitmap bitmap, int maxFileSize, int maxDimensions) {
Bitmap resizedBitmap;
if (bitmap.getWidth() > maxDimensions || bitmap.getHeight() > maxDimensions) {
resizedBitmap = getResizedBitmap(bitmap,
maxDimensions);
} else {
resizedBitmap = bitmap;
}
byte[] bitmapData = getByteArray(resizedBitmap);
while (bitmapData.length > maxFileSize) {
bitmapData = getByteArray(resizedBitmap);
}
return bitmapData;
}
public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image,
width,
height,
true);
}
private static byte[] getByteArray(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,
80,
bos);
return bos.toByteArray();
}
关于java - 将位图压缩到Android中的特定字节大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919925/