private static Image GetDIBImage(MemoryStream ms) { byte[] dib = ms.ToArray(); BITMAPINFOHEADER infoHeader = Helpers.ByteArrayToStructure <BITMAPINFOHEADER>(dib); IntPtr gcHandle = IntPtr.Zero; try { GCHandle handle = GCHandle.Alloc(dib, GCHandleType.Pinned); gcHandle = GCHandle.ToIntPtr(handle); if (infoHeader.biSizeImage == 0) { infoHeader.biSizeImage = (uint)(infoHeader.biWidth * infoHeader.biHeight * (infoHeader.biBitCount >> 3)); } using (Bitmap bmp = new Bitmap(infoHeader.biWidth, infoHeader.biHeight, -(int)(infoHeader.biSizeImage / infoHeader.biHeight), infoHeader.biBitCount == 32 ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb, new IntPtr((long)handle.AddrOfPinnedObject() + infoHeader.OffsetToPixels + ((infoHeader.biHeight - 1) * (int)(infoHeader.biSizeImage / infoHeader.biHeight))))) { return(new Bitmap(bmp)); } } finally { if (gcHandle != IntPtr.Zero) { GCHandle.FromIntPtr(gcHandle).Free(); } } }