Created
May 17, 2020 15:20
-
-
Save ArinFaraj/1100b47826aea3fd5037971c4aa98c7b to your computer and use it in GitHub Desktop.
this is a way to remove a color from a bitmap image in wpf (subtract the color)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private static WriteableBitmap Subtract(Color color, BitmapSource bitmap) | |
| { | |
| unsafe | |
| { | |
| if (bitmap == null) return null; | |
| var writeableBitmap = new WriteableBitmap(bitmap); | |
| var width = writeableBitmap.PixelWidth; | |
| var height = writeableBitmap.PixelHeight; | |
| var stride = writeableBitmap.BackBufferStride; | |
| var bytesPerPixel = (writeableBitmap.Format.BitsPerPixel + 7) / 8; | |
| const int tolerance = 200; | |
| writeableBitmap.Lock(); | |
| var pBackBuffer = writeableBitmap.BackBuffer; | |
| var pBuff = (byte*)pBackBuffer.ToPointer(); | |
| for (var row = 0; row < height; row++) | |
| { | |
| for (var col = 0; col < width; col++) | |
| { | |
| if (Math.Abs(pBuff[row * stride + col * bytesPerPixel + 0] - color.B) >= tolerance || | |
| Math.Abs(pBuff[row * stride + col * bytesPerPixel + 1] - color.G) >= tolerance || | |
| Math.Abs(pBuff[row * stride + col * bytesPerPixel + 2] - color.R) >= tolerance) continue; | |
| pBuff[row * stride + col * bytesPerPixel + 0] = 0; | |
| pBuff[row * stride + col * bytesPerPixel + 1] = 0; | |
| pBuff[row * stride + col * bytesPerPixel + 2] = 0; | |
| pBuff[row * stride + col * bytesPerPixel + 3] = 0; | |
| } | |
| } | |
| writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, (int)writeableBitmap.Width, | |
| (int)writeableBitmap.Height)); | |
| writeableBitmap.Unlock(); | |
| return writeableBitmap; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment