Search code examples
c#visual-studiowindows-phone-8image-processingcolors

Windows Phone 8 - change color in bitmap


How can I change one color of bitmap to another?


Solution

  • Your solution uses GetPixel and SetPixel methods which are really slow. You can get the same result much faster working on pixels directly. But before that we have to know how to convert Color to int, because pixels in WriteableBitmap are represented by int array.

    Some of my apps use this method to manipulate pixels and I wanted to do it as fast as possible, so never use SetPixel or GetPixel (eg. MC Skin Editor, MC Skin Viewer).

    To convert Color to int I made this simple extension:

    public static int ToInt(this Color color)
    {
        return unchecked((int)((color.A << 24) | (color.R << 16) | (color.G << 8) | color.B));
    }
    

    So now, your method could look like this:

    public static WriteableBitmap ChangeColor(WriteableBitmap writeableBitmapOriginal, Color originalColor, Color newColor)
    {
        var writeableBitmapNew = new WriteableBitmap(writeableBitmapOriginal);
        originalColorInt = originalColor.ToInt();
        newColorInt = newColor.ToInt();
    
        for (int i = 0; i < writeableBitmapNew.Pixels.Length; i++)
            if (writeableBitmapNew.Pixels[i] == originalColorInt)
                writeableBitmapNew.Pixels[i] = newColorInt;
        return writeableBitmapNew;
    }