【问题标题】:Bitmap array format in C#C#中的位图数组格式
【发布时间】:2014-11-20 06:30:45
【问题描述】:

我有以下代码使用带有数据的数组创建位图*

//Here create the Bitmap to the know height, width and format
Bitmap bmp = new Bitmap( 5,7,PixelFormat.Format1bppIndexed);  
//Create a BitmapData and Lock all pixels to be written 
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),   
ImageLockMode.WriteOnly, bmp.PixelFormat);
//Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(data, 0, bmpData.Scan0, data.Length);     
//Unlock the pixels
bmp.UnlockBits(bmpData);
bmp.Save("BitMapIcon.bmp",ImageFormat.Bmp);

我的输入数组(数据):

byte[5] data = {0xff,0xff,0xff,0xff,0xff}

问题:

  1. 用于位图输入的数据数组* 是否只有每个像素的值(在此 格式是 0 和 1 ) ?
  2. 为什么要传递一些 0xff 值的数组 像素不是黑色的?
  3. 宽度大小可以小于 1 字节吗?

【问题讨论】:

  • 按照惯例,黑色总是 0x00 或等效值。

标签: c# .net bitmap


【解决方案1】:

你有两个问题:

  • 首先,索引格式的默认调色板使用 0 表示黑色,1 表示白色。所以你的代码实际上是在尝试初始化一个白色的位图,而不是一个黑色的

  • 第二个问题,更重要的是,您没有完全初始化位图。这与您的第三个问题有关:位图的宽度允许小于 1 个字节的像素,但位图 data 本身可能需要比位图的单个扫描线更多的像素。

确实,由于位图的对齐要求,您的位图的“步幅”为 4 个字节。因此,您总共需要 28 个字节才能完全初始化位图。

此代码将按照您想要的方式初始化位图:

//Here create the Bitmap to the know height, width and format
Bitmap bmp = new Bitmap(5, 7, PixelFormat.Format1bppIndexed);
//Create a BitmapData and Lock all pixels to be written 
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
//Copy the data from the byte array into BitmapData.Scan0
byte[] data = new byte[bmpData.Stride * bmpData.Height];

for (int i = 0; i < data.Length; i++)
{
    data[i] = 0xff;
}
Marshal.Copy(data, 0, bmpData.Scan0, data.Length);
//Unlock the pixels
bmp.UnlockBits(bmpData);

如果您确实想要黑色像素,请使用 0x00 而不是 0xff

【讨论】:

  • 嗨,我唯一不明白的是,如果我的数据 [] 现在的大小为 28 字节,但我只想操作 5x7=35 位,该数据数组中的索引现在负责“图像视图” "。
  • 每行占用 4 个字节。但只有前 5 位很重要。您可以将其他 23 位设置为任何您想要的,它不会有任何区别。它们只是作为位图数据结构中的填充。因此,如果您想在位级别操作 5x7 图像,只需处理前五位即可。说了这么多:如果你真的总是在处理这么小的位图,我怀疑你可以毫无问题地使用Bitmap.SetPixel() 方法。它相对较慢,但在这里您可能会发现它已经足够快了。
  • 谢谢。索引格式不支持 bitmap.SetPixel()。
  • 啊,对。忘了那个。也不能画到一个(不能得到Graphics 实例)。有点玩弄它,然后。 :)
猜你喜欢
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 2017-08-01
相关资源
最近更新 更多