Search code examples
c#.netcolorssystem.drawing

changing pixel color in C#


hello i'm working on program that read whole image and change the color of green line to red line for example i have this image this image and i want the c# program get the green pixels and convert it to red i tried this code : `

public Bitmap ReadImgPixel(Bitmap img)
{
        Bitmap pic = new Bitmap(img,img.Width,img.Height);
        int a1 = img.Width;
        int a2 = img.Height;
        System.Drawing.Color[,] pixels = new System.Drawing.Color[a1,a2];

        for (int i = 0;i< img.Width ; i++)
        {
            for(int j=0; j < img.Height; j++)
            {

               System.Drawing.Color pxl = img.GetPixel(i, j);
                if (pxl != System.Drawing.Color.White)
                {
                    pic.SetPixel(i, j, System.Drawing.Color.Red);
                }

            }

        }
         return pic;
     }

but the result was the whole image is changing to red how to fix it !!


Solution

  • Have you tried debugging (you could have easily found out why all pixels turned red)? Your whole picture turns red because the if statement is always true.

    The reason this happens is because you are comparing structs. However, your pixel name will not say White (what you are comparing to), but it will contain a string with the hex value of your color (e.g. ffffff). So it is never equal, because the objects are different. Therefore, since you want to see if the ARGB values are the same, you have to compare these.

    Change your statement to this to compare the ARGB values:

    if (pxl.ToArgb() != Color.White.ToArgb())
    

    Also make sure you check Cody Gray's comment, since your code is absolutely not efficient. If efficiency is important to you, try a different approach, but that's outside the scope of this question.