【问题标题】:How to create 1024x1024 RGB bitmap image of white?如何创建白色的 1024x1024 RGB 位图图像?
【发布时间】:2021-01-17 07:25:37
【问题描述】:

问这个问题很尴尬却找不到答案。

我试过这个是徒劳的。

Image resultImage = new Bitmap(image1.Width, image1.Height, PixelFormat.Format24bppRgb);

using (Graphics grp = Graphics.FromImage(resultImage)) 
{
    grp.FillRectangle(
        Brushes.White, 0, 0, image1.Width, image1.Height);
    resultImage = new Bitmap(image1.Width, image1.Height, grp);
}

我基本上想在 C# 中用白色填充 1024x1024 RGB 位图图像。我该怎么做?

【问题讨论】:

  • 您正在为您的问题寻找解决方案,但您的代码解决了我的问题,谢谢 :)

标签: c#


【解决方案1】:

你差点就吃完了:

private Bitmap DrawFilledRectangle(int x, int y)
{
    Bitmap bmp = new Bitmap(x, y);
    using (Graphics graph = Graphics.FromImage(bmp))
    {
        Rectangle ImageSize = new Rectangle(0,0,x,y);
        graph.FillRectangle(Brushes.White, ImageSize);
    }
    return bmp;
}

【讨论】:

    【解决方案2】:

    您正在为resultImage 分配一个新图像,从而覆盖您之前创建白色图像的尝试(顺便说一句,这应该会成功)。

    所以只需删除该行

    resultImage = new Bitmap(image1.Width, image1.Height, grp);
    

    【讨论】:

      【解决方案3】:

      另一种方法,

      创建单位位图

      var b = new Bitmap(1, 1);
      b.SetPixel(0, 0, Color.White);
      

      并缩放它

      var result = new Bitmap(b, 1024, 1024);
      

      【讨论】:

      • 我喜欢这种方法!谢谢!
      • 小心!当您使用Color.FromArgb() 时,您将在缩放位图时获得渐变。最好使用来自@LeeHarrison 的solution
      【解决方案4】:

      Graphics.Clear(Color)

      Bitmap bmp = new Bitmap(1024, 1024);
      using (Graphics g = Graphics.FromImage(bmp)){g.Clear(Color.White);}
      

      【讨论】:

        【解决方案5】:

        根据您的需要,BitmapSource 可能适合。您可以使用 Enumerable.Repeat() 快速用 0xff(即白色)填充字节数组。

        int w = 1024;
        int h = 1024;
        byte[] pix = Enumerable.Repeat((byte)0xff, w * h * 4).ToArray();
        SomeImage.Source = BitmapSource.Create(w, h, 96, 96, PixelFormats.Pbgra32, null, pix, w * 4);
        

        【讨论】:

          猜你喜欢
          • 2016-08-19
          • 2012-05-14
          • 2018-04-01
          • 1970-01-01
          • 2011-11-22
          • 1970-01-01
          • 2011-12-28
          • 2018-08-19
          • 1970-01-01
          相关资源
          最近更新 更多