您可以使用下面的代码。请注意,它目前仅适用于每像素32位的PixelFormat,即Brg32
,Bgra32
,Prgba32
。
public static BitmapSource Invert(BitmapSource source)
{
// Calculate stride of source
int stride = (source.PixelWidth * source.Format.BitsPerPixel + 7)/8;
// Create data array to hold source pixel data
int length = stride * source.PixelHeight;
byte[] data = new byte[length];
// Copy source image pixels to the data array
source.CopyPixels(data, stride, 0);
// Change this loop for other formats
for (int i = 0; i < length; i += 4)
{
data[i] = (byte)(255 - data[i]); //R
data[i + 1] = (byte)(255 - data[i + 1]); //G
data[i + 2] = (byte)(255 - data[i + 2]); //B
//data[i + 3] = (byte)(255 - data[i + 3]); //A
}
// Create a new BitmapSource from the inverted pixel buffer
return BitmapSource.Create(
source.PixelWidth, source.PixelHeight,
source.DpiX, source.DpiY, source.Format,
null, data, stride);
}
您现在可以使用这样的:
brush.ImageSource = Invert(new BitmapImage(new Uri(@"C:\temp\dog.png")));
所以
成为 ![enter image description here](https://i.stack.imgur.com/oB7Pg.png)
[反转图像在C#中更快(HTTP的可能重复://作为一个说明,UriKind.Relative的机智(#)(#)(#)stackoverflow.com/questions/33024881/invert-image-faster-in-c-sharp) –
作为一个说明,UriKind.Relative机智h绝对URI看起来可疑。 – Clemens
@AliBahrainezhad是winform,我使用wpf – Luca