c# - 从数组创建位图对象

标签 c# winforms bitmap

我有一个类似于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);

最佳答案

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

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;

关于c# - 从数组创建位图对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11989567/

相关文章:

c# - 使用 MemoryStream 的 xml 末尾有很多意外的 "nul"字符

c# - 如何在字符串中添加特殊字符

vb.net - 为表单创建分部类

c# - 使用 ErrorProvider 组件在 WinForms 中进行数据验证

java - OpenCV、安卓 : color detection from particular area or portion of an image?

c# - 奇怪的正则表达式行为 - 只匹配第一个和最后一个捕获组

winforms - powershell中的Windows窗体,在页面底部显示图片框

android - 在给定矩形边界的情况下以编程方式缩放和居中 imageView

c++ - 使用(MFC 的)CImage::SetPixel() 改变像素的颜色

c# - 如何打开 Excel 文件并在 WPF 中查看?