C#: Bitmap Creation using bytes array

前端 未结 2 1074
萌比男神i
萌比男神i 2021-01-21 23:50

I am trying to dynamically create a Bitmap Image using byte array using following code

Bitmap GetImage()
{
    IntPtr  ip = Marshal.AllocCoTaskMem(imagesize);

          


        
相关标签:
2条回答
  • 2021-01-22 00:23

    The simplest way may be to create the bitmap (although in similar code I've used a normal byte[] and then a fixed block, rather than directly using AllocCoTaskMem), and then create a second Bitmap of the same size. Call Graphics.FromImage on the second bitmap, then Graphics.DrawImage using the first bitmap to effectively copy the contents of the first bitmap onto the second. You can then call Dispose on the first bitmap, release the memory, and use the second bitmap which is basically a copy.

    There may well be a more efficient way to do it if you're more proficient with image stuff, but if you're just looking for a way to get it to work, it's a starting point :)

    EDIT: zachrrs's comment does indeed make things easier using the Bitmap(Image) constructor:

    using (Bitmap original = new Bitmap(...))
    {
        Bitmap copy = new Bitmap(originalImage);
        // Then return "copy" from your method, and you can free the
        // memory
    }
    
    0 讨论(0)
  • 2021-01-22 00:44

    If you know the dimensions in advance, why not creating the bitmap and use the Bitmap.LockBits method to get the input buffer address?

    0 讨论(0)
提交回复
热议问题