从数组创建位图对象

从数组创建位图对象

问题描述:

我有一个数组,如byte[] pixels。有没有办法在不复制数据的情况下从pixels创建一个bitmap对象?我有一个小图形库,当我需要在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); 
+0

这是有点相关我想:http://*.com/questions/1580130/high-speed-performance c-sharp-image-filtering-in-c-sharp – Patrick 2012-08-16 14:52:58

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

Bitmap Constructor (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; 
+0

当我尝试绘制newBitmap时,它会抛出Access Violation:/它说它应该从Paint方法(PaintEventArgs)中调用。 – zgnilec 2012-08-16 14:59:49

你不能只是使用:

System.Drawing.Bitmap.FromStream(new MemoryStream(bytes)); 

我不认为这些方法调用会做任何复制,因为没有在MSDN中表示这样:http://msdn.microsoft.com/en-us/library/9a84386f

+3

很多人似乎都错过了这样的事实,即FromStream方法期望流将包含位图头信息以及RGB或像素值。 – Mozzis 2015-03-20 01:23:28