C#,带IntPtr的新Bitmap,ArgumentException

Ale*_*lex 2 c# exception bitmap

我有一个非常奇怪的问题.

这是我的简化代码,用于解释:

class Bitmap1
{
    public Bitmap nImage;
    public IntPtr data;


    public Bitmap1()
    {
        int w = 2450;
        int h = 2450;

        this.data = Marshal.AllocHGlobal(w*h);

        nImage = new Bitmap(w, h, w, PixelFormat.Format8bppIndexed, data);

    }
}
Run Code Online (Sandbox Code Playgroud)

wh等于2448时,如果我调用构造函数,一切都运行良好.

但是当h和w等于2450时,我ArgumentException看起来似乎是由"新的Bitmap(...)"启动的.

我无法理解,文档并没有说有限的尺寸Marshal.AllocHGlobal.

怎么了?还有其他方法可以做我想要的吗?

非常感谢你.

Cod*_*aos 5

stride类型:System.Int32整数,指定一条扫描线的开头与下一条扫描线之间的字节偏移量.这通常(但不是必须)像素格式中的字节数(例如,每像素16位的2)乘以位图的宽度.传递给此参数的值必须是四的倍数.

http://msdn.microsoft.com/en-us/library/zy1a2d14.aspx

所以你需要以下内容:

int w = 2450;
int h = 2450;
int s = 2452;//Next multiple of 4 after w

this.data = Marshal.AllocHGlobal(s*h);

nImage = new Bitmap(w, h, s, PixelFormat.Format8bppIndexed, data);
Run Code Online (Sandbox Code Playgroud)

这意味着每行之间只有2个字节,只是填充而不是位图本身的一部分.在进行指针运算时,您显然需要这样做,s*y+x而不是w*y+x考虑填充.