How to replace one set of color 'shades' w

2019-07-21 16:42发布

问题:

I'm looking for a 'magic' function that will take an image and return a copy but with one set of color shades replaced with another set.

e.g. I have a picture of a Red fish: It has various greyscales and Black and White but is essentially various shades of red. I would like to pass it to this 'magic' function and tell it to change its Color.Red shades to equivalent Color.Yellow shades and so on. Just simple (rainbow) colors would be sufficient.

I have seen many code snippets here and on the internet but they seem to concentrate on replacing a single color with another or using a threshold, which works well enough interactively but isn't quite magic enough.

The images I want to apply this to are not photographs or anything too complicated, just icons or simple sprites and the like. (I'm just bored of creating copies in an image editor!)

Anyone have anything like this?

回答1:

You can accomplish this using the FromAhsb() as displayed in Oliver's answer at Image hue modification in C# (or any other function which lets you create colors from HSB values). Using this function you can easily change the hue of images as following:

var image = new Bitmap("D:\\fish.png"); // location of your image
var color = Color.Red; //The color in the hue you want to change the image.

for (var x = 0; x < image.Width; x++)
{
    for (int y = 0; y < image.Height; y++)
    {
        Color originalColor = image.GetPixel(x, y);
        Color changedColor = FromAhsb(originalColor.A, color.GetHue(), originalColor.GetSaturation(), originalColor.GetBrightness());
        image.SetPixel(x,y, changedColor);
    }
}

image.Save("D:\\new_fish.png", System.Drawing.Imaging.ImageFormat.Png); // location of your new image

This produces the following result:

From to