您可以使用下面的代碼。請注意,它目前僅適用於每像素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")));
所以 成爲
[反轉圖像在C#中更快(HTTP的可能重複://作爲一個說明,UriKind.Relative的機智(#)(#)(#)stackoverflow.com/questions/33024881/invert-image-faster-in-c-sharp) –
作爲一個說明,UriKind.Relative機智h絕對URI看起來可疑。 – Clemens
@AliBahrainezhad是winform,我使用wpf – Luca