[英]Android Compress a Bitmap
I have wrote this method before I noticed there is a compress method in Bitmap class. 在我注意到Bitmap类中有一个compress方法之前,我已经写过这个方法。
/**
* 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;
}
I was wondering, compare to the built in Compress
method, should I keep using this one, or switch to use the built in one? 我想知道,与内置的Compress
方法相比,我应该继续使用这个,还是切换到使用内置的? what is the difference? 有什么不同?
Basically
What you are doing in the above code is just resizing the image ,which will not loose much of the quality of the image since you use the SampleSize
. 您在上面的代码中所做的只是调整图像大小,因为您使用SampleSize
不会失去图像的大部分质量。
compress(Bitmap.CompressFormat format, int quality, OutputStream stream)
It is used when you want to change the imageFormat
you have Bitmap.CompressFormat JPEG
当您想要更改imageFormat
时使用它,您可以使用Bitmap.CompressFormat JPEG
Bitmap.CompressFormat PNG
Bitmap.CompressFormat WEBP
or to reduce the quality
of the image using the quality
parameter 0 - 100
. Bitmap.CompressFormat PNG
Bitmap.CompressFormat WEBP
或降低quality
使用的图像的quality
参数0 - 100
。
Your method is in line with Loading Large Bitmap guidelines 您的方法符合加载大位图指南
compress() methods converts a large bitmap to a small one: compress()方法将大位图转换为小位图:
I would use your method if I needed to load bitmap from a file to ImageViews of different sizes. 如果我需要将文件中的位图加载到不同大小的ImageView,我会使用您的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.