【问题标题】:graphics undefined drawing to the destination bitmap C#图形未定义绘制到目标位图 C#
【发布时间】:2016-09-21 20:11:30
【问题描述】:

这是我发布的第一个问题。所以请善待我,但是关于如何改进我的提问以提高可读性的 cmets 非常受欢迎。

我尝试使用图形旋转一组短裤。

我将一组短裤读取到图像中,使用图形对其进行旋转,然后将其存储回短裤数组中。 但是我遇到了图形处理程序没有按预期工作,所以我将我的代码剥离到它看起来像这样:

它首先使用 Marshal.Copy() 将一个简单的 short 数组 (source48) 复制到 src Bitmap。

   short[] source48= new short[]{255,255,255,2,2,2,5,5,5];
   int srcCols=3,int srcRows=1;
   Drawing.Bitmap srcImage = new Drawing.Bitmap(srcCols,srcRows, System.Drawing.Imaging.PixelFormat.Format48bppRgb);   
   System.Drawing.Imaging.BitmapData data = srcImage.LockBits(
                new Drawing.Rectangle(0, 0, srcCols, srcRows),
                System.Drawing.Imaging.ImageLockMode.WriteOnly,
                System.Drawing.Imaging.PixelFormat.Format48bppRgb);
   // Copy the source buffer to the bitmap
   Marshal.Copy(source48, 0, data.Scan0, source48.Length);
   // Unlock the bitmap of the input image again.
   srcImage.UnlockBits(data);
   data = null;             

然后它创建一个新的位图“rotatedImage”并使用图形用“srcImage”填充“rotatedImage”(我现在跳过实际的旋转)

  Drawing.Bitmap rotatedImage = new drawing.Bitmap(srcCols,srcRows,System.Drawing.Imaging.PixelFormat.Format48bppRgb);
  rotatedImage.SetResolution(srcImage.HorizontalResolution, srcImage.VerticalResolution);
  using (Drawing.Graphics g = Drawing.Graphics.FromImage(rotatedImage))
  {
        g.Clear(Drawing.Color.Black);
        g.DrawImage(srcImage, 0, 0);
  }

然后我从“旋转”图像中读取 rawData。

 data = rotatedImage.LockBits(
                new Drawing.Rectangle(0, 0, srcCols, srcRows),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format48bppRgb);
 // Copy the bulk from the output image bitmap to a 48bppRGB buffer
 short[] destination48 = new short[9];
 Marshal.Copy(data.Scan0, destination48, 0, destination48.Length);

不幸的是,我发现destination48 充满了 {252,252,252,2,2,2,5,5,5];而不是预期的:[255,255,255,2,2,2,5,5,5]。

我尝试填充背景、绘制矩形等。 我真的不知道目标位图中的数据不包含源图像中的数据的原因是什么。图形的准确性是否受到影响?

【问题讨论】:

  • 如果先保存Bitmap并检查图像会怎样?
  • 另外,Format48bppRgb * srcCols * srcRows != sizeof(short) * srcCols * srcRows
  • Marshall.copy 需要以字节为单位的大小。试试destination.lengrh * sizeof(短)
  • @JeroenvanLangen 如果我尝试得到一个超出范围的异常。仍然发现一些未定义的行为。如果我将 short 数组更改为: [1,0,0,2,0,0,3,0,0,4,0,0,5,0,0,6,0,0] 和 srcRows=3 & src 列=2。结果是 [0 0 0 2 0 0 2 0 0 0 0 0 5 0 0 5 0 0]。我现在很困惑。

标签: c# graphics bitmap drawing


【解决方案1】:

在 MSDN 上,there is a comment 声明:

PixelFormat48bppRGB、PixelFormat64bppARGB 和 PixelFormat64bppPARGB 每个颜色分量(通道)使用 16 位。 GDI+ 版本 1.0 和 1.1 可以读取每通道 16 位的图像,但此类图像会转换为每通道 8 位的格式以进行处理、显示和保存。每个 16 位颜色通道可以保存 0 到 2^13 范围内的值。

我敢打赌,这就是导致此处准确性下降的原因。

也许你可以选择Format24bppRgb,每条短线使用两个像素;当还设置 srcCols 使其值加倍时,它似乎返回了您的示例的正确结果。

【讨论】:

  • 是的,没错。这绝对是原因!我想这是该方法固有的吗?所以我想没有办法解决这个问题(比如重新缩放图像)?
  • @Deltadaniel 我唯一能想到的是使用Format24bppRgb 和每个短片两个“像素”。
猜你喜欢
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多