如何以编程方式从颜色数组创建24bpp位图?

Joh*_*res 2 c# bitmap

我试图以编程方式从包含颜色数据的数组创建位图.使用下面的代码,当在图片框中显示时,我会并排获得3个重复的扭曲图像.谁能告诉我哪里出错了?

    public Bitmap CreateBM(int[,] imgdat)
    {
        Bitmap bitm = new Bitmap(imgdat.GetUpperBound(1) + 1, imgdat.GetUpperBound(0) + 1, PixelFormat.Format24bppRgb);
        BitmapData bitmapdat = bitm.LockBits(new Rectangle(0, 0, bitm.Width, bitm.Height), ImageLockMode.ReadWrite, bitm.PixelFormat);
        int stride = bitmapdat.Stride;

        byte[] bytes = new byte[stride * bitm.Height];
        for (int r = 0; r < bitm.Height; r++)
        {
            for (int c = 0; c < bitm.Width; c++)
            {
                Color color = Color.FromArgb(imgdat[r, c]);
                bytes[(r * bitm.Width) + c * 3] = color.B;
                bytes[(r * bitm.Width) + c * 3 + 1] = color.G;
                bytes[(r * bitm.Width) + c * 3 + 2] = color.R;
            }
        }


        System.IntPtr scan0 = bitmapdat.Scan0;
        Marshal.Copy(bytes, 0, scan0, stride * bitm.Height);
        bitm.UnlockBits(bitmapdat);

        return bitm;
    }
}
Run Code Online (Sandbox Code Playgroud)

Qua*_*ter 5

您希望stride每行增加索引而不是仅增加索引bitm.Width.

bytes[(r * stride) + c * 3] = color.B;
bytes[(r * stride) + c * 3 + 1] = color.G;
bytes[(r * stride) + c * 3 + 2] = color.R;
Run Code Online (Sandbox Code Playgroud)