Much faster ToBitmap() code, use int[] instead of byte[]

Jun 3, 2010 at 6:20 AM

As title, if we use int[] instead of byte[] to do the "RgbaToArgbPremultiplied" processing, it will be at least twice faster.

public static WriteableBitmap ToBitmap(this ImageTools.ImageBase image, IImageFilter filter)
{
    Guard.NotNull(image, "image");

    WriteableBitmap bitmap = new WriteableBitmap(image.Width, image.Height);

    ImageBase temp = image;

    // If there is a specified filter...
    if (filter != null)
    {
        // Clone the image and apply filter to it:
        temp = new ImageBase(image);

        filter.Apply(temp);
    }

    byte[] pixels = temp.GetPixels();
    int[] raster = bitmap.Pixels;
    Buffer.BlockCopy(pixels, 0, raster, 0, pixels.Length);

    for (int i = 0; i < raster.Length; i++)
    {
        int abgr = raster[i];
        int a = (abgr >> 24) & 0xff;
        float m = a / 255f;
        int argb = a << 24 |
                    (int)((abgr & 0xff) * m) << 16 |
                    (int)(((abgr >> 8) & 0xff) * m) << 8 |
                    (int)(((abgr >> 16) & 0xff) * m);
        raster[i] = argb;
    }

    bitmap.Invalidate();

    return bitmap;
}

Coordinator
Jun 7, 2010 at 2:20 PM
Nice, will integrate it in a future version :)
Jul 29, 2010 at 12:12 PM

It's not only faster, this also fixes pixelised output and black background issues.

 

Thanks a lot!

Coordinator
Jul 29, 2010 at 12:21 PM
Yes, its part of the latest version in source control.