【发布时间】:2016-04-18 12:41:29
【问题描述】:
有没有办法我可以在 android 中将 115kb 的图像压缩为 4kb 而不影响它的大小?。只是降低它的质量?
我只知道使用
BitmapFactory.Options 减小尺寸和质量
Bitmap.compress 不提供指定字节大小的选项。
public Bitmap compressImage(String imagePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bmp = BitmapFactory.decodeStream(new FileInputStream(imagePath),null, options);
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeStream(new FileInputStream(imagePath),null, options);
return bmp;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
【问题讨论】:
-
为什么需要这个?避免OOME?这无济于事! ... 解码 Bitmap 的文件是 4KB 还是 1MB 都没有关系 ... Bitmap 对象将占用相同数量的内存,仅取决于 Bitmap 宽度和高度以及像素格式
-
@Selvin 我不需要这个来避免 OOME。实际上我正在尝试实现一个图像共享应用程序,如whatsapp,用户将在下载之前看到图像的外观。因此,我正在考虑通过 googles GCM 向用户发送与原始尺寸相同但质量较低的图像,这将数据负载限制为 4kb :(
-
没有其他方法可以像尝试使用不同的
q值的bitmap.compress(Bitmap.CompressFormat.JPG, q)...但是您可以尝试将文件拆分为4kb 的图片...或使用Google drive API(或任何其他可以存储)并仅发送链接 -
@Selvin 如果我使用这种方法,我无法判断图像字节超过 4kb。如果他们这样做并且我通过谷歌 GCM 发送他们,我会收到错误 MessageTooBig
-
嗯?为什么...
for(int q = 100; q > 0; q--) {OutputStream out = getOutputFromFile(file);bitmap.compress(Bitmap.CompressFormat.JPG, q, out); if(checkFileSize(file) < 4000) {sendFile(file); break;}}...当然这不是最佳方式(它更像是蛮力)也可能需要很长时间...
标签: android bitmap bitmapfactory