0

I'm trying to replace white color with green, but code below doesn't change color.

Code:

private static MagickImage ChangeWhiteColor(MagickImage Image, Color TargetColor)
{
    Image.Opaque(MagickColor.FromRgb((byte)255, (byte)255, (byte)255), 
        MagickColor.FromRgb(TargetColor.R,
        TargetColor.G,
        TargetColor.B));
    return Image;
}

UPD I tried to change composite gravity and operator, but nothing changes.

What I should do?

Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90
pnzrfst1
  • 189
  • 2
  • 9
  • 1
    Can make your question a little more detailed? Include what you've tried and the results. – gloomy.penguin Mar 09 '17 at 20:47
  • 1
    I don't know Magick.Net but you need to find the `fuzz` parameter and add some fuzz before the replacement because colours are not precise - especially with lossy JPEGs, so if you allow say 20% margin for error with some fuzz, then you will likely get the result you seek. – Mark Setchell Mar 10 '17 at 11:31
  • I tried your code with an image containing a red (R=255,G=0,B=0) square and it worked. Are you sure that the color you want to replace in tour image is a "perfect" 255,0,0, red? – Andrea Mar 31 '17 at 08:07

1 Answers1

4

Your code works if you have to replace a perfectly white color (R=255, G=255, B=255 or #ffffff if you prefer).

If you are trying to replace a color that is similar (but not exactly equal) to white you can use ColorFuzz to introduce a tolerance.

To achieve this you can add a new fuzz parameter to your method that should look like this:

private static MagickImage ChangeWhiteColor(MagickImage Image, Color TargetColor, int fuzz)
{
    Image.ColorFuzz = new Percentage(fuzz);
    Image.Opaque(MagickColor.FromRgb((byte)255, (byte)255, (byte)255), 
        MagickColor.FromRgb(TargetColor.R,
        TargetColor.G,
        TargetColor.B));
    return Image;
}

Consider for example the following image that contains three white rectangles. Under each shape I reported the RGB values. The first rectangle on the left is filled with pure white color, while the second and the third are filled with very light greys that are very similar to the white color:

enter image description here

Your original code will only replace the first white rectangle on the left (since fuzz default value is 0%):

enter image description here

Running the modified code with fuzz=2 will replace the first and the second white rectangle, but not the third:

enter image description here

Running the modified code with fuzz=6 will replace all the three white rectangles:

enter image description here

You can adjust fuzz value (percentage) in order to match the colors you have to replace.

More info about fuzz here.

Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90
Andrea
  • 11,801
  • 17
  • 65
  • 72