Effective way to replace a specific color in Bitmap / Image

In my image in grayscale, I need to find a certain value and replace it with some color, for example, yellow. Here is the code that I have now, but it is not as fast as I need. Is there a more efficient way to achieve this? I was red in the ColorMatrix class , but could not find a way to replace a single value without affecting the entire image.

unsafe
{
    byte stlThres = 115;

    int bytePerPixel = Image.GetPixelFormatSize(kpImageViewer1.Image.PixelFormat) / 8;
    var data = kpImageViewer1.Image.LockBits(new Rectangle(0, 0, kpImageViewer1.Image.Width, kpImageViewer1.Image.Height), ImageLockMode.WriteOnly, kpImageViewer1.Image.PixelFormat);
    for (int y = 0; y < data.Height; y++)
    {
        byte* row = (byte*)data.Scan0 + (y * data.Stride);

        for (int x = 0; x < data.Width; x++, row += bytePerPixel)
        {
            if (row[0] == stlThres)
            {
                row[0] = 0; //b
                row[1] = 255; //g
                row[2] = 255; //r
                if (bytePerPixel == 4)
                {
                    row[3] = 255; //a
                }
            }
        }
    }
    kpImageViewer1.Image.UnlockBits(data);
}
+4
source share
1 answer

4- , 4 (8 ), 256- , row[0], 32 - int.

+1

All Articles