Change pixel color in C #

Hi I am working on a program that reads a whole image and changes the color of the green line to a red line, for example I have this image this imageand I want a C # program to get green pixels and convert them 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 as a result the whole image changed to red, how to fix it.

+3


source to share


1 answer


Have you tried debugging (you could easily find out why all the pixels turned red)? Your whole picture turns red because the operator is if

always there true

.

The reason for this is because you are comparing structures. However, your pixel name

won't say White

(what you are comparing), but it will contain a string with hex

your color value (for example ffffff

). Therefore, he is never equal, because the objects are different. Therefore, since you want to know if the values ​​are the same ARGB

, you must compare them.

Change your operator to this to compare values ARGB

:



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

      

Also make sure you check Cody Gray's comment as your code is completely ineffective. If efficiency is important to you, try a different approach, but that is beyond the scope of this question.

+6


source







All Articles