How in Bitmap to leave only the necessary colors of pixels, and the rest to turn, for example, in black?

Of course, I would like to make a decision more easily.

    1 answer 1

    The easiest option is via GetPixel and SetPixel , but it will work rather slowly.

    It is better to use Scan0 and convert the image to an array of Scan0 that correspond to the color of each pixel — the PixelFormat.Format32bppArgb format is suitable for this - colors are represented by 4 bytes and int also 4 bytes.

    Below is the processing code in VB.NET, it can be easily rewritten in C #.

    This code replaces one color with another, but allows comparing to ignore the alpha channel (and save it when replacing). If any other condition is needed, then the corresponding comparison and assignment must be replaced.

     Public Shared Sub ReplaceColor(ByVal Bmp As Bitmap, ByVal OldColor As Color, ByVal NewColor As Color, Optional ByVal IgnoreAlpha As Boolean = False) Dim BmpData As BitmapData = Bmp.LockBits(New Rectangle(Nothing, Bmp.Size), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb) Dim ArgbData(BmpData.Stride * BmpData.Height / 4 - 1) As Integer Dim Mask As Integer = If(IgnoreAlpha, (1 << 24) - 1, -1), NotMask As Integer = Not Mask Dim OldVal As Integer = ((((((CInt(OldColor.A) << 8) Or OldColor.R) << 8) Or OldColor.G) << 8) Or OldColor.B) And Mask Dim NewVal As Integer = ((((((CInt(NewColor.A) << 8) Or NewColor.R) << 8) Or NewColor.G) << 8) Or NewColor.B) And Mask Marshal.Copy(BmpData.Scan0, ArgbData, 0, ArgbData.Length) For Q As Integer = 0 To ArgbData.Length - 1 If (ArgbData(Q) And Mask) = OldVal Then ArgbData(Q) = (ArgbData(Q) And NotMask) Or NewVal Next Q Marshal.Copy(ArgbData, 0, BmpData.Scan0, ArgbData.Length) Bmp.UnlockBits(BmpData) End Sub