C# Bitmap using unsafe code

2019-03-12 08:03发布

问题:

I'm using the following code to make image masks in C#:

for(int x = 0; x < width; x++)
{
    for(int y = 0; y < height; y++)
    {
        bmp.SetPixel(x,y,Color.White);
    }
}

for(int x = left; x < width; x++)
{
    for(int y = top; y < height; y++)
    {
        bmp.SetPixel(x,y,Color.Transparent);
    }
}

But it's WAY too slow... What is the unsafe equivalent to this? Will it be allot faster?

In the end I do a bmp.Save() in PNG format.

UPDATE:

After reading through http://www.bobpowell.net/lockingbits.htm as suggested by MusiGenesis, I made it work using the following code (for anyone who needs it):

Bitmap     bmp = new Bitmap(1000,1000,PixelFormat.Format32bppArgb);
BitmapData bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width,bmp.Height), 
                                  System.Drawing.Imaging.ImageLockMode.ReadWrite, 
                                  bmp.PixelFormat);

int PixelSize=4;

unsafe 
{
    for(int y=0; y<bmd.Height; y++)
    {
        byte* row=(byte *)bmd.Scan0+(y*bmd.Stride);

        for(int x=0; x<bmd.Width; x++)
        {
            row[x*PixelSize]     = 0;   //Blue  0-255
            row[x*PixelSize + 1] = 255; //Green 0-255
            row[x*PixelSize + 2] = 0;   //Red   0-255
            row[x*PixelSize + 3] = 50;  //Alpha 0-255
        }
    }
}

bmp.UnlockBits(bmd);

bmp.Save("test.png",ImageFormat.Png);

Alpha channel: 0 being fully transparent, 255 being no transparency on that pixel.

I'm sure you can easily modify the loop for painting a rectangle :)

回答1:

Check out this tutorial on using LockBits:

http://www.BobPowell.net/lockingbits.htm

This will be orders of magnitude faster than using SetPixel.



标签: c# bitmap unsafe