Home > Uncategorized > Converting a Bitmap to a pixel array

Converting a Bitmap to a pixel array

I was looking for some high performance code to convert a bitmap into a 2D byte array, this is what I came up with.
first I have a class called pixel.
public class pixel


  public byte red;

  public byte green;

  public byte blue;



then I read it using some Unsafe code thus:

public pixel[,] BitmapToArray(Bitmap b)


pixel[,] bmpData=new pixel[b.Width,b.Height];

// GDI+ still lies to us – the return format is BGR, NOT RGB.

BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

int stride = bmData.Stride;

System.IntPtr Scan0 = bmData.Scan0;



byte * p = (byte *)(void *)Scan0;

int nOffset = stride – b.Width*3;

int nWidth = b.Width * 3;

for(int y=0;y<b.Height;++y)


for(int x=0; x < nWidth; ++x )




case 0:

bmpData[x/3,y] =

new pixel();

bmpData[x/3,y].blue = (



case 1:

bmpData[x/3,y].green = (



case 2:

bmpData[x/3,y].red = (byte)(p[0]);





p += nOffset;




return bmpData;




Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: