C# Snippet for Accessing Bitmap Data with Unsafe Code

Since GetPixel is slow and I keep having to access bitmap data with unsafe code, I thought it would be a nice thing to make into a snippet.

Paste the following code into a text file, and save it as “usbmp.snippet”. In Visual Studio go to “Tools/Code Snippets Manager…” and import the file.


<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Unsafe Bitmap Processing</Title>
      <Shortcut>usbmp</Shortcut>
      <Description>Code for accessing a bitmaps pixel data with unsafe code</Description>
      <Author>Jonathan Mathews Software</Author>
    </Header>
    <Snippet>
      <Declarations>
        <Object>
          <ID>bitmap</ID>
          <Type>System.Drawing.Bitmap</Type>
          <ToolTip>Replace with a bitmap in your application.</ToolTip>
          <Default>bitmap</Default>
        </Object>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[unsafe
                {
                    BitmapData data = $bitmap$.LockBits(
                                                    new Rectangle(new Point(0, 0), $bitmap$.Size), 
                                                    ImageLockMode.ReadOnly, 
                                                    PixelFormat.Format24bppRgb);

                    byte* pointer = (byte*)data.Scan0;

                    int padding = data.Stride - ($bitmap$.Width * 3);

                    for (int y = 0; y < $bitmap$.Height; y++)
                    {
                        for (int x = 0; x < $bitmap$.Width; x++)
                        {
                            // pointer[2]; // R
                            // pointer[1]; // G
                            // pointer[0]; // B
                            $end$

                            pointer += 3;
                        }

                        pointer += padding;
                    }

                    $bitmap$.UnlockBits(data);
                }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Notes:

  • Use it by entering “usbmp” in your code, and pressing tab twice. Edit the bitmap name to your bitmap.
  • You’ll need to add using System.Drawing.Imaging; if it’s not there already.
  • If you want to edit the pixels instead of just reading them, change “ImageLockMode.ReadOnly”.
Creative Commons License
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.