Direct instantiation of Bitmap from unsafe memory
-
Hi there, I'm quite exhausted now trying to directly set the Scan0 Paramater of a Bitmap to avoid slow copying bitmaps in memory. Basically, I try to do the following: 1.) I have a buffer containing already loaded Bitmap files in memory. Fo r performance reasons, this buffer is allocated via VirtualAlloc and therefore unsafe. 2.) I'm passing a UnmanagedMemoryStream with a subportion of the buffer to my Drawing function, pointing to the beginning of the bitmap file. 3.) I'll try to instantiate a bitmap, using the Streampointer to use the buffer directly and draw it to the screen ( or better, a backbuffer). This looks like this:
// linear buffer containing bmp file unsafe { UnmanagedMemoryStream mstr= new UnmanagedMemoryStream((byte*)buf.ptrStart.ToPointer(), buf.Count, buf.Count, FileAccess.Read); } BitmapData bmd; BufferBitmap = new Bitmap(1920, 1080); ImageLockMode fLock = ImageLockMode.UserInputBuffer; // causes "Invalid Parameter" exception at the moment bmd = BufferBitmap.LockBits(new Rectangle(0,0,1920,1080), fLock,PixelFormat.Format24bppRgb); unsafe { bmd.Scan0 = new IntPtr(mstr.PositionPointer+14); } BufferBitmap.Unlock(bmd); GfxBuffer.Graphics.DrawImageUnscaled(BufferBitmap, new Point(0,0));
Well, all I get is a "Invalid Parameter" Exception when setting the LockBits with the UserInputBuffer Flag, or, if I use the ReadWrite Flag, I would probably have to use the buffer the Bitmapobject manages, which would be an unnecessary copy operation. I just want to display the bitmap I've already in memory which the smallest possible effort. Does anybody have an idea whats going wrong here ? According to some examples I found, it should work this way. Interestingly, even if a try to pass a buffer allocated with Marshal.AllocHGlobal the LockBits operation fails... The buffer contains valid data, because this code works, but I think, this causes every time an instantiation and copy procedure:// GfxBuffer.Graphics.DrawImageUnscaled(Bitmap.FromStream(mstr,false), new Point(0,0));
Bye, Florian