【问题标题】:How to invert an image如何反转图像
【发布时间】:2016-12-05 17:19:40
【问题描述】:

我要在按钮上设置 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);

谢谢

【问题讨论】:

  • Invert image faster in C#的可能重复
  • 请注意,带有绝对 URI 的 UriKind.Relative 看起来很可疑。
  • @AliBahrainezhad 用于 winform,我正在使用 wpf

标签: c# wpf image


【解决方案1】:

您可以使用下面的代码。请注意,它目前仅适用于每像素 32 位的 PixelFormat,即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")));

所以 变成

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 2022-11-19
    • 2011-02-28
    • 1970-01-01
    相关资源
    最近更新 更多