1

I am trying to write a code that extracts pixel color values for each pixel in a bitmap file. For such purpose I have imported the bmp as a bitmap object and I have used Bitmap.GetPixel(x,y) method but it was not fast enough for my application. One of my colleagues gave me an advice; I think I can use fopen to open the file itself, parse the byte data to an array. Do any of you have any idea? Using fopen method is not a must, I can use anything.

Thanks in advance.

talkanat
  • 329
  • 1
  • 3
  • 7
  • It's not that easy. You need to convert different formats to your target format from raw data and that's not an easy job. At least this is how much I know. You can use `byte[] data = System.IO.File.ReadAllBytes('file.bmp')` to get your data, but I have spoken about formatting. – MahanGM Aug 02 '13 at 09:22
  • The fopen() function isn't any faster or different from FileStream or File.ReadAllBytes() or Image.FromFile(). Focus on using unsafe pointers, *that's* the alternative for GetPixel(). Use Bitmap.LockBits(), there are a ton of google hits out there. – Hans Passant Aug 02 '13 at 12:01

1 Answers1

2

You can use either unsafe code block or you can utilize the Marshal class. I'd solve this way:

public static byte[] GetBytesWithMarshaling(Bitmap bitmap)
{
    int height = bitmap.Height;
    int width = bitmap.Width;

    //PixelFormat.Format24bppRgb => B|G|R => 3 x 1 byte
    //Lock the image
    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
    // 3 bytes per pixel
    int numberOfBytes = width * height * 3;
    byte[] imageBytes = new byte[numberOfBytes];

    //Get the pointer to the first scan line
    IntPtr sourcePtr = bmpData.Scan0;
    Marshal.Copy(sourcePtr, imageBytes, 0, numberOfBytes);

    //Unlock the image
    bitmap.UnlockBits(bmpData);

    return imageBytes;
}
Balázs Szántó
  • 1,440
  • 3
  • 15
  • 29
  • This was the first answer, and it worked perfectly. Thank you. But I was not able to understand what marshal class is about, and what lockbits method does, could you please explain them briefly? – talkanat Aug 02 '13 at 19:24
  • 1
    1, Lockbits => During the lifetime of the objects their position in the memory could be changed, for example after a garbage collection. To prevent this behaviour the bitmap is locked/fixed in the memory. I think It works like the fixed statement. 2, Marshal is a static class with bunch of methods to interop between managed and unmanaged code, allocate unmanaged memory, etc. – Balázs Szántó Aug 02 '13 at 20:00