从数组创建位图对象

3
我有一个像byte[] pixels这样的数组。有没有办法从那个pixels创建一个bitmap对象而不需要复制数据?我有一个小型图形库,当我需要在WinForms窗口上显示图像时,我只需将数据复制到一个bitmap对象中,然后使用绘制方法。我能避免这个复制过程吗?我记得我在某个地方看到过,但也许我的记忆力不好。
编辑:我尝试了这段代码,它可以工作,但是这样安全吗?
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);

这与编程有关,我认为这个链接可能会对你有所帮助:http://stackoverflow.com/questions/1580130/high-speed-performance-of-image-filtering-in-c-sharp - Patrick
2个回答

6

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

Bitmap 构造函数 (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;

当我尝试绘制newBitmap时,它会抛出访问冲突:/ 它说应该从Paint方法(PaintEventArgs)中调用。 - apocalypse

0

5
很多人似乎忽视了FromStream方法需要流中包含位图头信息以及RGB或像素值这一事实。 - Mozzis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接