如何反转图像

时间:2016-12-05 17:19:41

标签: c# wpf image

我在按钮上设置了一个png图像:

Button btn = new Button();
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(@"C:\temp\dog.png", UriKind.Relative));
btn.Background = brush;

我想让它倒置(意味着负面图像)。

类似的东西:

btn.Background = Invert(brush);

由于

1 个答案:

答案 0 :(得分:3)

您可以使用以下代码。请注意,它目前仅适用于每像素32位的PixelFormats,即Brg32Bgra32Prgba32

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 hereenter image description here

相关问题