6

I have raw pixel data coming from a camera in RGB8 format which I need to convert to a Bitmap. However, the Bitmap PixelFormat only seems to support RGB 16, 24, 32, and 48 formats.

I attempted to use PixelFormat.Format8bppIndexed, but the image appears discolored and inverted.

public static Bitmap CopyDataToBitmap(byte[] data)
{
    var bmp = new Bitmap(640, 480, PixelFormat.Format8bppIndexed);

    var bmpData = bmp.LockBits(
                         new Rectangle(0, 0, bmp.Width, bmp.Height),
                         ImageLockMode.WriteOnly, bmp.PixelFormat);

    Marshal.Copy(data, 0, bmpData.Scan0, data.Length);

    bmp.UnlockBits(bmpData);

    return bmp;
}

Is there any other way to convert this data type correctly?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Barry Tormey
  • 2,966
  • 4
  • 35
  • 55
  • Helpful articles: [this](http://msdn.microsoft.com/en-us/library/windows/desktop/ee719797(v=vs.85).aspx) and [this](http://msdn.microsoft.com/en-us/library/ms969901.aspx) – Adriano Repetti Oct 02 '14 at 13:10
  • Curious: What type/model of camera produces that format? Also: [this](http://www.theimagingsource.com/en_US/support/documentation/icimagingcontrol-activex/PixelformatRGB8.htm) source says it is a 8bit monochrome format. – TaW Oct 02 '14 at 13:33
  • Another quote from [this source](http://www.theimagingsource.com/en_US/support/documentation/icimagingcontrol-activex/PixelformatRGB8.htm): _RGB is bottom-up, the first line has index (lines-1_ – TaW Oct 02 '14 at 13:41
  • Format8bppIndexed is correct format for your case. In addition, you need to make ColorPalette which maps pixel value 0 to RGB (0,0,0) ... 255 to RGB (255, 255, 255). See Image.Palette property. – Alex F Oct 02 '14 at 13:49
  • @TaW It is a Vista Ey2 iris scanner. – Barry Tormey Oct 02 '14 at 15:21
  • @AlexFarber I am not sure I follow. Could you provide an example? – Barry Tormey Oct 02 '14 at 15:25
  • Can you post a link to one or two example image files? And: Are they monochrome or colored? – TaW Oct 02 '14 at 15:47
  • @Taw monochrome. Grayscale. – Barry Tormey Oct 02 '14 at 15:48

1 Answers1

2

This creates a linear 8-bit grayscale palette in your image.

bmp.UnlockBits(bmpData);

var pal = bmp.Palette;
for (int i = 0; i < 256; i++) pal.Entries[i] = Color.FromArgb(i, i, i);
bmp.Palette = pal;

return bmp;

You will still need to invert the scan lines, maybe like this:

for (int y = 0; y < bmp.Height; y++)
     Marshal.Copy(data, y * bmp.Width, 
             bmpData.Scan0 + ((bmp.Height - 1 - y) * bmpData.Stride), bmpData.Stride);
TaW
  • 53,122
  • 8
  • 69
  • 111