【问题标题】:How to change color of a image in C#如何在C#中改变图像的颜色
【发布时间】:2018-03-26 19:49:31
【问题描述】:

我正在开发一个 Windows 应用程序,我在其中从服务器获取图像(黑色)。我下载该图像并将其显示在我的应用程序中。

有没有办法在代码中更改此图像的颜色(变为白色),因为我想显示白色图像,因为我有黑色背景。

如果我需要其他信息,请告诉我?

【问题讨论】:

  • 你有一张黑色背景的图片并将其更改为白色背景吗?
  • 没有。这不是我的要求。
  • @Rachel 请添加之前和之后的示例图片
  • @Rachel,您目前使用哪个图形库?也许 Win2D 可以做你需要的,因为 System.Drawing 在这里不是一个选项...see also here。你在控制服务器端吗?如果是,我建议让服务器为您准备图片的倒置版本。

标签: c# xaml windows-8.1


【解决方案1】:

取决于你想在这个兔子洞里走多远。

您可以将图像转换为32bit 并滚动您自己的图像处理例程以将黑色像素转换为白色像素。

以下是如何使用unsafe 关键字和Pointers 相当有效地实现此目的的示例。加入胡椒和盐调味

-unsafe (C# Compiler Options)

免责声明还有其他方法可以做到这一点,但是 YOLO

unsafe private void ConvertImage(string fromPath, string toPath)
{
    using (Bitmap orig = new Bitmap(fromPath))
    {
       using (Bitmap clone = new Bitmap(orig.Width, orig.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb))
       {
          var rect = new Rectangle(0, 0, clone.Width, clone.Height);
          using (Graphics gr = Graphics.FromImage(clone))
          {
             gr.DrawImage(orig, rect);
          }

          // lock the array for direct access
          var bitmapData = clone.LockBits(Bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
          // get the pointer
          var scan0Ptr = (int*)bitmapData.Scan0;
          // get the stride
          var stride = bitmapData.Stride / 4;

          var white = Color.White.ToArgb();
          var black = Color.Black.ToArgb();

          // scan all x
          for (var x = rect.Left; x < rect.Right; x++)
          {
             var pX = scan0Ptr + x;

             // scan all y
             for (var y = rect.Top; y < rect.Bottom; y++)
             {
                if (*(pX + y * stride) == black)
                {
                   *(pX + y * stride) = white;
                }
                else
                {
                   *(pX + y * stride) = black;
                }

             }
          }
          // unlock the bitmap
          clone.UnlockBits(bitmapData);

          clone.Save(toPath);
       }
    }
}

更新

改为反转图像

【讨论】:

  • 我的应用不支持位图和 System.Drawing
猜你喜欢
  • 1970-01-01
  • 2013-10-27
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多