我有一个URI图片文件,并想缩小它的大小以便上传。初始图像文件大小因手机而异(可能是2MB,也可能是500KB),但我希望最终大小约为200KB,以便上传。
根据我的了解,我至少有两种选择:
我考虑将图像宽度/高度最初调整到大于1000px(例如1024x768或其他尺寸),然后通过逐渐减小质量来压缩图像,直到文件大小大于200KB。以下是一个示例:
根据我的了解,我至少有两种选择:
- 使用BitmapFactory.Options.inSampleSize对原始图像进行子采样并获取较小的图像;
- 使用Bitmap.compress指定压缩质量来压缩图像。
我考虑将图像宽度/高度最初调整到大于1000px(例如1024x768或其他尺寸),然后通过逐渐减小质量来压缩图像,直到文件大小大于200KB。以下是一个示例:
int MAX_IMAGE_SIZE = 200 * 1024; // max final file size
Bitmap bmpPic = BitmapFactory.decodeFile(fileUri.getPath());
if ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) {
BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
bmpOptions.inSampleSize = 1;
while ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) {
bmpOptions.inSampleSize++;
bmpPic = BitmapFactory.decodeFile(fileUri.getPath(), bmpOptions);
}
Log.d(TAG, "Resize: " + bmpOptions.inSampleSize);
}
int compressQuality = 104; // quality decreasing by 5 every loop. (start from 99)
int streamLength = MAX_IMAGE_SIZE;
while (streamLength >= MAX_IMAGE_SIZE) {
ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
compressQuality -= 5;
Log.d(TAG, "Quality: " + compressQuality);
bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
byte[] bmpPicByteArray = bmpStream.toByteArray();
streamLength = bmpPicByteArray.length;
Log.d(TAG, "Size: " + streamLength);
}
try {
FileOutputStream bmpFile = new FileOutputStream(finalPath);
bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpFile);
bmpFile.flush();
bmpFile.close();
} catch (Exception e) {
Log.e(TAG, "Error on saving file");
}
有更好的方法吗?我应该尝试继续使用所有2个方法还是只用其中一个?谢谢