Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Bitmap using unsafe code
    text
    copied!<p>I'm using the following code to make image masks in C#:</p> <pre><code>for(int x = 0; x &lt; width; x++) { for(int y = 0; y &lt; height; y++) { bmp.SetPixel(x,y,Color.White); } } for(int x = left; x &lt; width; x++) { for(int y = top; y &lt; height; y++) { bmp.SetPixel(x,y,Color.Transparent); } } </code></pre> <p>But it's WAY too slow... What is the unsafe equivalent to this? Will it be allot faster? </p> <p>In the end I do a bmp.Save() in PNG format.</p> <p><strong>UPDATE:</strong></p> <p>After reading through <a href="http://www.bobpowell.net/lockingbits.htm" rel="noreferrer">http://www.bobpowell.net/lockingbits.htm</a> as suggested by MusiGenesis, I made it work using the following code (for anyone who needs it):</p> <pre><code>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&lt;bmd.Height; y++) { byte* row=(byte *)bmd.Scan0+(y*bmd.Stride); for(int x=0; x&lt;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); </code></pre> <p>Alpha channel: 0 being fully transparent, 255 being no transparency on that pixel.</p> <p>I'm sure you can easily modify the loop for painting a rectangle :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload