Android双线性图像缩小

时间:2014-02-07 12:37:16

标签: android bitmap filtering interpolation

我正在尝试使用双线性过滤缩小位图,但显然我的代码中有一些错误,因为图像看起来比最近邻居好或者只是使用android的下采样,但不如Image Magick的biliear过滤器好。

你在我的调整大小方法中看到了什么问题吗?

private Bitmap resize(Bitmap immutable, int reqWidth, int reqHeight) {
    Bitmap bitmap = Bitmap.createBitmap(reqWidth, reqHeight, Config.ARGB_8888);
    float scaleFactor = immutable.getHeight() / (float) reqHeight;
    for (int x = 1; x < reqWidth - 1; x++) {
        for (int y = 1; y < reqHeight - 1; y++) {
            float sx = x * scaleFactor;
            float sy = y * scaleFactor;
            int rx = (int) (x * scaleFactor);
            int ry = (int) (y * scaleFactor);

            final int tl = immutable.getPixel(rx, ry);
            final int tr = immutable.getPixel(rx + 1, ry);
            final int bl = immutable.getPixel(rx, ry+1 );
            final int br = immutable.getPixel(rx + 1, ry+1);

            float xC1 = sx- rx;
            float xC2 = 2-xC1;

            float yC1 = sy - ry;
            float yC2 = 2 - yC1;

            xC1/=2;
            xC2/=2;
            yC1/=2;
            yC2/=2;

            final float firstAlpha = (Color.alpha(tl) * xC2 + Color.alpha(tr) * xC1);
            final float firstRed = (Color.red(tl) * xC2 + Color.red(tr) * xC1);
            final float firstBlue = (Color.blue(tl) * xC2 + Color.blue(tr) * xC1);
            final float firstGreen = (Color.green(tl) * xC2 + Color.green(tr) * xC1);

            final float secondAlpha = (Color.alpha(bl) * xC2 + Color.alpha(br) * xC1);
            final float secondRed = (Color.red(bl) * xC2 + Color.red(br) * xC1);
            final float secondGreen = (Color.green(bl) * xC2 + Color.green(br) * xC1);
            final float secondBlue = (Color.blue(bl) * xC2 + Color.blue(br) * xC1);

            int finalColor = Color.argb((int) (yC2 * firstAlpha + yC1 * secondAlpha), (int) (yC2 * firstRed + yC1 * secondRed), (int) (yC2 * firstGreen + yC1
                    * secondGreen), (int) (yC2 * firstBlue + yC1 * secondBlue));
            bitmap.setPixel(x, y, finalColor);
        }
    }

    return bitmap;
}

My Result

而Image magick的结果如下: Image magick's result

1 个答案:

答案 0 :(得分:2)

当调用 BitmapFactory.Options :: inSampleSize-&gt; BitmapFactory.decodeResource() 时,Android会使用双线性缩减算法。

如此好的缩减算法(不是最近邻居)只包含2个步骤(加上计算输入/输出矩形裁剪的精确矩形):

  1. 使用 BitmapFactory.Options :: inSampleSize-&gt; BitmapFactory.decodeResource() 缩减,尽可能接近您需要但不低于它的分辨率
  2. 通过使用 Canvas :: drawBitmap()
  3. 缩小一点来获得精确的分辨率

    以下是SonyMobile如何解决此任务的详细说明:http://developer.sonymobile.com/2011/06/27/how-to-scale-images-for-your-android-application/

    以下是SonyMobile scale utils的源代码:http://developer.sonymobile.com/downloads/code-example-module/image-scaling-code-example-for-android/