代码在 C#WPF应用程序上工作正常,但由于我无法在表单应用程序中创建可写位图,因此无法在Windows Form application
上正确显示图像尝试使用Lockbits和Marshal Copy方法从字节创建Bitmap。图像格式有问题吗?
这是我目前的代码。我添加了 BytesToBitmap 函数,以 PixelFormat.Format32bppRgb 格式将字节转换为位图。
代码:
public partial class Form1 : Form
{
private KinectSensor sensor;
private Bitmap colorBmp;
private Bitmap depthBmp;
private byte[] colorPxl;
private byte[] depthPxl;
public Form1()
{
InitializeComponent();
}
public void formLoaded(object sender, EventArgs e)
{
foreach (var potenialK in KinectSensor.KinectSensors)
{
...
}
if (null != this.sensor)
{
this.sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
this.sensor.DepthStream.Enable(DepthImageFormat.Resolution320x240Fps30);
this.sensor.SkeletonStream.Enable();
this.colorPxl = new byte[this.sensor.ColorStream.FramePixelDataLength];
this.colorBmp = new Bitmap(this.sensor.ColorStream.FrameWidth, this.sensor.ColorStream.FrameHeight);
this.depthBmp = new Bitmap(this.sensor.DepthStream.FrameWidth, this.sensor.DepthStream.FrameHeight);
this.sensor.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(SensorAllFrameReady);
try
{
this.sensor.Start();
}
catch (IOException)
{
this.sensor = null;
}
}
}
private void SensorAllFrameReady(object sender, AllFramesReadyEventArgs e)
{
using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
{
if (colorFrame != null)
{
colorFrame.CopyPixelDataTo(this.colorPxl);
this.pictureBox1.Image = BytesToBitmap(colorPxl, 640, 480);
}
}
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (depthFrame != null)
{
depthPxl = GenerateColoredBytes(depthFrame);
this.pictureBox2.Image = BytesToBitmap(depthPxl, 320, 240);
}
}
}
private byte[] GenerateColoredBytes(DepthImageFrame depthFrame)
{
...
return pixels;
}
public static Bitmap BytesToBitmap(byte[] pixelData, int height, int width)
{
var bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
var bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat);
var ptr = bitmapData.Scan0;
Marshal.Copy(pixelData, 0, ptr, pixelData.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
答案 0 :(得分:0)
所以这才有效。在将colorframe
直接传递给BytesToBitmap
函数时,我可以正确地看到框架。
代码:
public static Bitmap ImageToBitmap(ColorImageFrame Image)
{
byte[] pixeldata = new byte[Image.PixelDataLength];
Image.CopyPixelDataTo(pixeldata);
Bitmap bmap = new Bitmap(Image.Width, Image.Height, PixelFormat.Format32bppRgb);
BitmapData bmapdata = bmap.LockBits(
new Rectangle(0, 0, Image.Width, Image.Height),
ImageLockMode.WriteOnly,
bmap.PixelFormat);
IntPtr ptr = bmapdata.Scan0;
Marshal.Copy(pixeldata, 0, ptr, Image.PixelDataLength);
bmap.UnlockBits(bmapdata);
return bmap;
}