如何以编程方式从颜色数组创建 24bpp 位图?
我正在尝试以编程方式从包含颜色数据的数组创建位图。使用下面的代码,当在图片框中显示时,我会并排获得 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;
}
}
I am trying to programatically create a bitmap from an array that contains color data. With the code below, I get 3 duplicate distorted images side by side when displayed in a picturebox. Can somebody tell me where it's going wrong?
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您希望每行将索引增加
stride
,而不是仅仅增加bitm.Width
。You want to increase the index by
stride
every row instead of just bybitm.Width
.