tags:

views:

637

answers:

1

I'm trying to write an application that converts 48 bit-per-pixel PNG files to a proprietary (Bayer) format.

The code (courtesy here) below works great for some PNG file formats, but when I try a bona fide 48 bit PNG the code throws an exception - is there an alternative?

    static public byte[] BitmapDataFromBitmap(Bitmap objBitmap)
    {
        MemoryStream ms = new MemoryStream();
        objBitmap.Save(ms, ImageFormat.BMP);  // GDI+ exception thrown for > 32 bpp
        return (ms.GetBuffer());
    }

    private void Bayer_Click(object sender, EventArgs e)
    {
        if (this.pictureName != null)
        {
            Bitmap bmp = new Bitmap(this.pictureName);
            byte[] bmp_raw = BitmapDataFromBitmap(bmp);
            int bpp = BitConverter.ToInt32(bmp_raw, 28); // 28 - BMP header defn.

            MessageBox.Show(string.Format("Bits per pixel = {0}", bpp));
        }
    }
+3  A: 

The BMP encoder doesn't support 48bpp formats. You can get a crack at the pixels with the Bitmap.LockBits() method. Although the MSDN Library article for PixelFormat says that 48bpp is treated like 24bpp images, I do in fact see 6 byte pixels with this code:

  Bitmap bmp = new Bitmap(@"c:\temp\48bpp.png");
  BitmapData bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
    ImageLockMode.ReadOnly, PixelFormat.Format48bppRgb);
  // Party with bd.Scan0
  //...
  bmp.UnlockBits(bd);
Hans Passant
Thanks that worked perfectly.
Jamie