0

I'm looking for algorithm that is able to do something like this:

Repaint image foreground and keep shades

The algorithm should change the color of an image with a transparent background. But it should not only set the color like bitmap.SetPixel(x, y, newColor). instead it should respect the shadows of the foreground.

Currently I use the following algorithm:

public static Image Foreground(this Image xImage, Color xColor)
{
    //FOREGROUND
    if (xImage == null) return null;
    Bitmap bitmap = new Bitmap(xImage);

    //LOOP PIXELS
    for (int x = 0; x < bitmap.Width; x++)
        for (int y = 0; y < bitmap.Height; y++)
            if (bitmap.GetPixel(x, y).A != 0)
            {
                Color color = bitmap.GetPixel(x, y);
                int a = color.A;
                int r = Math.Abs(xColor.R - color.R);
                int g = Math.Abs(xColor.G - color.G);
                int b = Math.Abs(xColor.B - color.B);
                bitmap.SetPixel(x, y, Color.FromArgb(a, r, g, b));
            }

    return bitmap;
}

It works well if you repaint from black to white. But if you repaint from white to orange it dosn't work well.

Is there any better solution?

NetMage
  • 26,163
  • 3
  • 34
  • 55
Mar Tin
  • 2,132
  • 1
  • 26
  • 46
  • 1
    Look into [Color Matrix](https://stackoverflow.com/questions/51526858/c-sharp-color-an-image-with-shadows/51533537?r=SearchResults&s=1|69.2681#51533537) – TaW Mar 25 '19 at 11:19
  • @TaW That was what I'm looking for! Thank you a lot. I have only one little issue: when use the color Matrix for the images I use, only the outline (between transparent and black) change the color. Example image: [link](https://www.iconexperience.com/_img/o_collection_png/dark_grey/512x512/plain/lock.png) I don't know what's going wrong. :/ – Mar Tin Mar 25 '19 at 12:57
  • 1
    Can't see what you mean in the image. Is it the right one? Can you post the original image you are working with? Note the the matrix is multplying the new color into the old one. If the old one is Black, ie (0,0,0) it will stay (0,0,0,). You would have to lighten it first. ColorMatrix can do that too. [See here](https://docs.rainmeter.net/tips/colormatrix-guide/) for a nice guide! – TaW Mar 25 '19 at 14:08
  • @TaW this is exactly what happen. The base of my images is black (0,0,0), only the outline contains different colors because of a resize effect. I think a invertation should solve the problem. By the way, the guid is amazing. Thanks for sharing! – Mar Tin Mar 26 '19 at 05:35

0 Answers0