【问题标题】:Code explanation for bitmap conversion位图转换的代码说明
【发布时间】:2016-07-01 13:57:09
【问题描述】:

https://stackoverflow.com/a/2574798/159072

public static Bitmap BitmapTo1Bpp(Bitmap img) 
{
  int w = img.Width;
  int h = img.Height;
  //
  Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
  BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);

为什么要进行这种加法和除法?

  byte[] scan = new byte[(w + 7) / 8];
  for (int y = 0; y < h; y++) 
  {
    for (int x = 0; x < w; x++) 
    {////Why this condition check?
      if (x % 8 == 0) 
      //Why divide by 8?
      scan[x / 8] = 0;
      Color c = img.GetPixel(x, y);
      //Why this condition check?
      if (c.GetBrightness() >= 0.5)
      { 
           // What is going on here?
           scan[x / 8] |= (byte)(0x80 >> (x % 8));
      }
    }
    // Why Martial.Copy() called here?
    Marshal.Copy(scan, 0, (IntPtr)((long)data.Scan0 + data.Stride * y), scan.Length);
  }
  bmp.UnlockBits(data);
  return bmp;
}

【问题讨论】:

    标签: c#-4.0 bitmap


    【解决方案1】:

    代码使用了一些基本的位黑客技术,这是必需的,因为它需要设置位,并且您可以在 C# 中寻址的最小存储元素是一个字节。我故意避免使用 BitArray 类。

       int w = img.Width;
    

    我将位图的Width和Height属性复制到一个局部变量中以加快代码速度,属性太贵了。请记住,w 是位图中的像素数,它表示最终图像中的数。

       byte[] scan = new byte[(w + 7) / 8];
    

    scan 变量将像素存储在位图的一个扫描行中。 1bpp 格式每个像素使用 1 位,因此扫描行中的总字节数为 w / 8。我添加 7 以确保该值向上舍入,这是必要的,因为整数除法总是截断。 w = 1..7 需要 1 个字节,w = 8..15 需要 2 个字节,依此类推。

       if (x % 8 == 0) scan[x / 8] = 0;
    

    x % 8 表达式表示位数,x / 8 是字节数。此代码在扫描行中的下一个字节前进时将所有像素设置为黑色。另一种方法是在外部循环中重新分配 byte[] 或使用 for 循环将其重置回 0。

       if (c.GetBrightness() >= 0.5)
    

    当源像素足够亮时,像素应设置为白色。否则,它将留在黑色。使用 Color.Brightness 是一种避免处理人眼对亮度的非线性感知(亮度 ~= 0.299 * red + 0.587 * green + 0.114 * blue)的简单方法。

       scan[x / 8] |= (byte)(0x80 >> (x % 8));
    

    在扫描线中设置一个位为白色。如前所述,x % 8 是位数,它将 0x80 向右移动位数,它们以这种像素格式以相反的顺序存储。

    【讨论】:

      猜你喜欢
      • 2011-11-26
      • 2012-06-25
      • 2013-09-12
      • 2017-01-23
      • 2014-09-21
      • 2016-06-01
      • 2015-01-13
      • 2015-08-16
      • 2010-11-25
      相关资源
      最近更新 更多