1
代碼工作得很好上C#WPF應用程序,但並不能夠在Windows Form application
正確顯示圖像作爲我不能創建表格應用程序中的可寫位圖所以嘗試使用以創建從字節位圖Lockbits和Marshal Copy方法。圖像格式有問題嗎?超高動力學V1 C#傾斜顯示圖像正常
這是我當前的代碼。我添加了一個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;
}