灰度较大的Bitmap图像很慢

时间:2014-06-01 13:27:43

标签: android performance image-processing bitmap

我将图像加载到Bitmap对象中。我当时想要做的是灰度存储在Bitmap对象中的图像。

我使用以下功能执行此操作:

public static Bitmap grayscale(Bitmap src)
{
    // constant factors
    final double GS_RED = 0.299;
    final double GS_GREEN = 0.587;
    final double GS_BLUE = 0.114;

    // create output bitmap
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    // pixel information
    int A, R, G, B;
    int pixel;

    // get image size
    int width = src.getWidth();
    int height = src.getHeight();

    // scan through every single pixel
    for(int x = 0; x < width; ++x)
    {
        for(int y = 0; y < height; ++y)
        {
            // get one pixel color
            pixel = src.getPixel(x, y);

            // retrieve color of all channels
            A = Color.alpha(pixel);
            R = Color.red(pixel);
            G = Color.green(pixel);
            B = Color.blue(pixel);

            // take conversion up to one single value
            R = G = B = (int)(GS_RED * R + GS_GREEN * G + GS_BLUE * B);

            // set new pixel color to output bitmap
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }

    // return final image
    return bmOut;
}

它工作正常,但速度非常慢。不适用于640x480等“小”图像。但在我的情况下,图像是3264x2448。在操作完成之前,这需要几秒钟......

所以我想知道像我现在一样扫描每个像素是否真的是最好的方法?有没有更好更快的方法来转换图像的颜色?

1 个答案:

答案 0 :(得分:0)

我怀疑扫描每个像素是最快的方式(它可能是最慢的)。

来自here的经过重构的代码看起来很有希望,因为它使用的是Android API:

public Bitmap toGrayscale(Bitmap bmpOriginal) {     
    int height = bmpOriginal.getHeight();
    int width = bmpOriginal.getWidth();   
    Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(bmpGrayscale);
    Paint paint = new Paint();
    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);
    ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
    paint.setColorFilter(f);
    c.drawBitmap(bmpOriginal, 0, 0, paint);
    return bmpGrayscale;
}