在我注意到 Bitmap 类中有一个压缩方法之前,我已经编写了此方法。
/**
* Calcuate how much to compress the image
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1; // default to not zoom image
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;
}
return inSampleSize;
}
/**
* resize image to 480x800
* @param filePath
* @return
*/
public static Bitmap getSmallBitmap(String filePath) {
File file = new File(filePath);
long originalSize = file.length();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize based on a preset ratio
options.inSampleSize = calculateInSampleSize(options, 480, 800);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap compressedImage = BitmapFactory.decodeFile(filePath, options);
return compressedImage;
}
我想知道,与内置Compress
方法相比,我应该继续使用这种方法,还是切换到使用内置方法? 有什么区别?
您的方法符合加载大位图准则
- 磁盘上的大文件
- 内存中的小位图
compress(( 方法将大位图转换为小位图:
- 内存中的大位图
- 磁盘上的小位图(IOStream((可能采用不同的格式(
如果我需要将位图从文件加载到不同大小的 ImageViews,我会使用您的方法。
Basically
您在上面的代码中所做的只是调整图像大小,这不会因为您使用SampleSize
而失去太多图像的质量。
compress(Bitmap.CompressFormat format, int quality, OutputStream stream)
当您想要更改imageFormat
时使用它Bitmap.CompressFormat JPEG
Bitmap.CompressFormat PNG
Bitmap.CompressFormat WEBP
或使用quality
参数0 - 100
降低图像的quality
。