C# 通过int数组设置非托管映像

C# 通过int数组设置非托管映像,c#,image,aforge,C#,Image,Aforge,我有一个8字节的数组,我想把它放入一个长度为4(向下)乘以宽度为2(向右)的位图中。我的代码: unsafe { IntPtr pixels = Marshal.AllocHGlobal(8); Marshal.WriteByte(pixels, 0 * Marshal.SizeOf(typeof(Byte)), 0); Marshal.WriteByte(pixels, 1 * Marshal.SizeOf(typeof(Byte)), 255); Marsh

我有一个8字节的数组,我想把它放入一个长度为4(向下)乘以宽度为2(向右)的位图中。我的代码:

unsafe
{
    IntPtr pixels = Marshal.AllocHGlobal(8);

    Marshal.WriteByte(pixels, 0 * Marshal.SizeOf(typeof(Byte)), 0);
    Marshal.WriteByte(pixels, 1 * Marshal.SizeOf(typeof(Byte)), 255);
    Marshal.WriteByte(pixels, 2 * Marshal.SizeOf(typeof(Byte)), 0);
    Marshal.WriteByte(pixels, 3 * Marshal.SizeOf(typeof(Byte)), 255);

    Marshal.WriteByte(pixels, 4 * Marshal.SizeOf(typeof(Byte)), 0);
    Marshal.WriteByte(pixels, 5 * Marshal.SizeOf(typeof(Byte)), 0);
    Marshal.WriteByte(pixels, 6 * Marshal.SizeOf(typeof(Byte)), 0);
    Marshal.WriteByte(pixels, 7 * Marshal.SizeOf(typeof(Byte)), 0);

    var newImage = new UnmanagedImage(pixels, 2, 4, 1, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
    var myBM = newImage.ToManagedImage();
    myBM.Save("outputBM.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

    Marshal.FreeHGlobal(pixels);
}
问题在于,对于第一列,图像对应于我的数组:

但是,如果我试图改变:

Marshal.WriteByte(pixels, 4 * Marshal.SizeOf(typeof(Byte)), 0);
Marshal.WriteByte(pixels, 4 * Marshal.SizeOf(typeof(Byte)), 0);


我希望第二列第一行的像素变成白色。然而,这并没有发生。代码有什么问题吗?

您必须将
new UnmanagedImage()
stride
构造函数参数值设置为2

步幅:图像步幅(以字节为单位的行大小)

通过更改以下行:

var newImage = new UnmanagedImage(pixels, 2, 4, 2, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
代码将生成以下图像:

更改时:

生成的图像如下所示:


您必须将
new UnmanagedImage()
stride
构造函数参数值设置为2

步幅:图像步幅(以字节为单位的行大小)

通过更改以下行:

var newImage = new UnmanagedImage(pixels, 2, 4, 2, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
代码将生成以下图像:

更改时:

生成的图像如下所示:

Marshal.WriteByte(pixels, 4 * Marshal.SizeOf(typeof(Byte)), 255);