Pixel by Pixel Color Conversion WriteableBitmap => PNG Black only to Color with Transparency

廉价感情. 提交于 2019-12-01 06:46:58

This case is solved. I found the WriteableBitmapExtensions class written by Rene Schulte.

This extension class offers this function (and many many more...):

private const float PreMultiplyFactor = 1 / 255f;

public static void SetPixeli(this WriteableBitmap bmp, int index, byte a, Color color)
  {
     float ai = a * PreMultiplyFactor;
     bmp.Pixels[index] = (a << 24) | ((byte)(color.R * ai) << 16) | ((byte)(color.G * ai) << 8) | (byte)(color.B * ai);
  }

The routine to change the color looks now like this:

    /// <summary>
    /// Changes the color of every pixel in a WriteableBitmap with an alpha value > 0 to the desired color.
    /// </summary>
    /// <param name="wbmi"></param>
    /// <param name="color"></param>
    /// <returns></returns>
    private static WriteableBitmap ColorChange(WriteableBitmap wbmi, System.Windows.Media.Color color)
    {
        for (int pixel = 0; pixel < wbmi.Pixels.Length; pixel++)
        {
            byte[] colorArray = BitConverter.GetBytes(wbmi.Pixels[pixel]);
            byte blue         = colorArray[0];
            byte green        = colorArray[1];
            byte red          = colorArray[2];
            byte alpha        = colorArray[3];

            if (alpha > 0)
            {
                wbmi.SetPixeli(pixel, alpha, color);
            }
        }

        wbmi.Invalidate();
        return wbmi;
    }

You can download the work of Rene Schulte here:

http://dotnet.dzone.com/sites/all/files/WriteableBitmapExtensions.zip

The whole project can be found here:

http://writeablebitmapex.codeplex.com/

As no one answered this question here on SO, big gun salutes to Rene Schulte. YMMD! :)

By the way: I am using SVGs of the NounProject, convert them to PNGs in the desired size and then I use this methods to color them. As all the symbols in the NounProject are black, it's a good way to get high quality symbols.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!