2008-11-07 67 views
1

如何在C#中使用GDI的圖像創建每像素1位的遮罩?我想從中創建掩碼的圖像保存在System.Drawing.Graphics對象中。從圖像創建1bpp遮罩

我已經看到在循環中使用Get/SetPixel的例子,這些例子太慢了。我感興趣的方法是僅使用BitBlits的方法,如this。我只是無法讓它在C#中工作,任何幫助都非常感謝。

回答

6

試試這個:

using System.Drawing; 
using System.Drawing.Imaging; 
using System.Runtime.InteropServices; 

...

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); 
     for (int y = 0; y < h; y++) { 
     byte[] scan = new byte[(w + 7)/8]; 
     for (int x = 0; x < w; x++) { 
      Color c = img.GetPixel(x, y); 
      if (c.GetBrightness() >= 0.5) scan[x/8] |= (byte)(0x80 >> (x % 8)); 
     } 
     Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length); 
     } 
     bmp.UnlockBits(data); 
     return bmp; 
    } 

GetPixel()是緩慢的,你可以用一個不安全的字節加快步伐*。

+1

謝謝你nobugz!我已經編輯了原始問題,因爲我試圖避免Get/SetPixel循環。我很抱歉。 – 2008-11-09 13:57:03

2

你的意思是LockBits? Bob Powell概述了LockBits here;這應該提供對RGB值的訪問,以做你需要的。你可能也想看看ColorMatrix,like so

3

在Win32 C API中,創建單聲道蒙板的過程很簡單。

  • 創建一個與源位圖一樣大的未初始化的1bpp位圖。
  • 將其選爲DC。
  • 將源位圖選擇到DC中。
  • SetBkColor在目標DC上以匹配源位圖的遮罩顏色。
  • BitBlt使用SRC_COPY將源發送到目標。

對於獎勵分數,通常需要將面罩抹回源位圖(使用SRC_AND)以將面罩顏色歸零。