【发布时间】:2014-04-26 06:38:30
【问题描述】:
我正在使用培训材料中的 BitmapFun 在 GridView 中显示我的图像。但是代码返回的图像非常模糊。我在方法decodeSampledBitmapFromDescriptor 中跟踪到了ImageResizer 类的第184 行的罪魁祸首之一。
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
这是实际的方法
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while (halfHeight / inSampleSize > reqHeight && halfWidth / inSampleSize > reqWidth) {
inSampleSize *= 2;
}
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
long totalPixels = width * height / inSampleSize;
// Anything more than 2x the requested pixels we'll sample down further
final long totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels > totalReqPixelsCap) {
inSampleSize *= 2;
totalPixels /= 2;
}
}
return inSampleSize;
}
所以我想要的是不要在采样时如此激进。但这会导致一些问题:既然这是加载位图的官方建议,那么将采样更改为不那么激进有什么问题?有没有人不得不更改此代码以获得更好质量的图片?我的调查是否正确?即这段代码是我的图像模糊的原因吗?这不是问题/疑问的详尽清单,但这应该让读者对我的担忧有所了解。最后:如何在不影响 BitmapFun 目的的情况下解决这个问题?显然,我去 BitmapFun 是有原因的:我的应用程序运行不正常并且经常崩溃。现在它没有崩溃,但是图像太模糊了。
【问题讨论】:
-
“将采样更改为不那么激进有哪些问题”——您很可能会经常遇到 OutOfMemoryErrors,尤其是在内存较低的设备上。不过不要上当,因为您仍然可以使用 inSampleSize 遇到该错误,因为您使用的是较低质量的图像版本,所以发生这种错误的可能性要小得多。如果您看到“激进的”下采样,您可能正在使用较小的源图像和/或所需的 Width/Height 参数值不正确。
-
你可以试试我的下采样方式:stackoverflow.com/questions/16408505/…
标签: android caching bitmap android-lru-cache