BitmapFun向下采样我的图像过于积极

时间:2014-03-19 18:59:35

标签: android caching bitmap android-lru-cache

我正在使用培训材料中的BitmapFun在GridView中显示我的图像。但代码返回非常模糊的图像。我在方法ImageResizer中跟踪了一个罪魁祸首到了班级decodeSampledBitmapFromDescriptor的第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:我的应用程序运行不正常并且不断崩溃。现在它不会崩溃,但图像太模糊了。

1 个答案:

答案 0 :(得分:0)

我不得不更改此代码以获得更高质量的图片。

改变只是为了删除“附加逻辑”。最后一次循环使图像看起来非常模糊。

- EDIT ---

我认为“额外的逻辑”中存在一个导致模糊的错误。

totalPixels应该通过inSampleSize的平方来计算,因为图像是以x和y维度进行采样的。所以只需更改此行:

long totalPixels = width * height / (inSampleSize * inSampleSize);

以下是有关我案例的更多详情:

reqWidth = 357 reqHeight = 357

options.outWidth = 4128 options.outHeight = 3096

到达“附加逻辑”时,inSampleSize为8

所以,totalPixels = 1597536和totalReqPixelsCap = 254898(这是关闭的)