簡體   English   中英

C#中修改像素最快的方法是什么

[英]What is the fastest way to modify pixels in C#

我想將 bitmap 中的指定像素更改為透明。 方法如下:

        Bitmap bt = new Bitmap(Mybitmap);
        System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, Mybitmap.Width, Mybitmap.Height);
        BitmapData bmpdata = bt.LockBits(rect, ImageLockMode.ReadWrite, bt.PixelFormat);
        IntPtr ptr = bmpdata.Scan0;
        int bytes = Math.Abs(bmpdata.Stride) * bt.Height;
        byte[] rgbValues = new byte[bytes];
        Marshal.Copy(ptr, rgbValues, 0, bytes);
        int len = rgbValues.Length;

        for (int i = 0; i < len; i += 4)
        {
            //Some colors are already stored in this SpecificColor1ist, and pixels with the same color will be changed to transparent
            foreach (var item in SpecificColor1ist)
            {
                
                if ((rgbValues[i]==item.B)&&(rgbValues[i+1] == item.G)&&(rgbValues[i+2] == item.R))
                {
                    rgbValues[i + 3] = (byte)0;
                }
            }

        }
        System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
        bt.UnlockBits(bmpdata);
        return bt;

但是速度太慢了。 有什么辦法讓它更快嗎? 不安全的代碼也是可以接受的。

  1. 你有一個指向像素數據數組的指針,為什么不使用它Scan0 (你需要將你的方法設置為不安全的,並在項目的構建選項中適當地設置它)
  2. 你可以確保你的像素格式是 32 位。
  3. 您可以將 go 中的 rbg 值與 int 進行比較
  4. 使用 HashSet 進行更快的查找
  5. 使用按位&清除 apha 通道

例子

var colorHash = SpecificColor1ist
   .Select(x => x.ToArgb())
   .ToHashSet();

...

var data = bt.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);


var length = (int*)data.Scan0 + Mybitmap.Height * Mybitmap.Width;
for (var p = (int*)data.Scan0; p < length; p++)
   if(colorHash .Contains(*p))
      *p = (*p & 0xFFFFFF) // i think sets the alpha to 0

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM