从数组创建Bitmap对象

apo*_*pse 3 c# bitmap winforms

我有一个类似的数组byte[] pixels.有没有办法在不复制数据的情况下从中创建bitmap对象pixels?我有一个小图形库,当我需要在WinForms窗口上显示图像时我只是将该数据复制到一个bitmap对象,然后我使用draw方法.我可以避免这种复制过程吗?我记得我在某个地方看过它,但也许我的记忆很糟糕.

编辑:我试过这个代码并且它可以工作,但这样安全吗?

byte[] pixels = new byte[10 * 10 * 4];

pixels[4] = 255; // set 1 pixel
pixels[5] = 255;
pixels[6] = 255;
pixels[7] = 255;

// do some tricks
GCHandle pinnedArray = GCHandle.Alloc(pixels, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();

// create a new bitmap.
Bitmap bmp = new Bitmap (10, 10, 4*10, PixelFormat.Format32bppRgb, pointer);

Graphics grp = this.CreateGraphics ();
grp.DrawImage (bmp, 0, 0);

pixels[4+12] = 255; // add a pixel
pixels[5+12] = 255;
pixels[6+12] = 255;
pixels[7+12] = 255;

grp.DrawImage (bmp, 0, 40);
Run Code Online (Sandbox Code Playgroud)

Tim*_*mbo 6

有一个构造函数,它接受一个指向原始图像数据的指针:

位图构造函数(Int32,Int32,Int32,PixelFormat,IntPtr)

例:

byte[] _data = new byte[]
{
    255, 0, 0, 255, // Blue
    0, 255, 0, 255, // Green
    0, 0, 255, 255, // Red
    0, 0, 0, 255,   // Black
};

var arrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(_data,
        System.Runtime.InteropServices.GCHandleType.Pinned);

var bmp = new Bitmap(2, 2, // 2x2 pixels
    8,                     // RGB32 => 8 bytes stride
    System.Drawing.Imaging.PixelFormat.Format32bppArgb,
    arrayHandle.AddrOfPinnedObject()
);

this.BackgroundImageLayout = ImageLayout.Stretch;
this.BackgroundImage = bmp;
Run Code Online (Sandbox Code Playgroud)