集成新相机时触发Object reference not set to an instance of an object异常
相机集成中的NullReferenceException问题
问题说明
在软件中集成新相机时,无法正常接收视频画面,触发以下错误:
System.NullReferenceException: Object reference not set to an instance of an object
经调试确认,崩溃发生在代码的Latest_image.Source = NativeMethods.ToBitmapSource(image);这一行。
相关代码片段:
public void GetImageFromCamera() { lock (camera_stream_lock) { if (imageData != null) { //Stop and restart stopwatch to get average fps fps_stopwatch.Stop(); TimeSpan ts = fps_stopwatch.Elapsed; current_fps = 1000.0 / (double)ts.Milliseconds; fps_stopwatch.Reset(); fps_stopwatch.Start(); //var bitmapData = new BitmapDataAcquisition(); var image = new Bitmap(imageData.Width, imageData.Height,imageData.PixelFormat); var rect = new Rectangle(0, 0, width, height); var data = image.LockBits(rect, ImageLockMode.ReadWrite, imageData.PixelFormat); Marshal.Copy(imageData.Buffer, 0, data.Scan0, imageData.Buffer.Length); image.UnlockBits(data); current_image_count++; Latest_image.Source = null; //Convert and save latest image Latest_image.Source = NativeMethods.ToBitmapSource(image); } if (recordCameraStream && Latest_image != null) { //recording_buffer.Add(Latest_image.Source); } } }
排查方向与解决方法
Latest_image控件未初始化
代码后续判断了Latest_image != null,但崩溃发生在赋值行,说明此时Latest_image还未完成实例化(比如WPF控件未在XAML中声明,或窗口未加载完成就调用了该方法)。
解决:- 检查XAML中是否正确定义了
Latest_image控件,确保它在调用GetImageFromCamera前已完成初始化。 - 在赋值前增加空判断:
if (Latest_image != null) { Latest_image.Source = NativeMethods.ToBitmapSource(image); }
- 检查XAML中是否正确定义了
NativeMethods.ToBitmapSource返回null
自定义的转换方法可能存在逻辑缺陷,导致转换失败返回null,进而触发空引用错误。
解决:- 检查
ToBitmapSource的实现,确保能正确将Bitmap转为BitmapSource,示例实现:public static BitmapSource ToBitmapSource(Bitmap bitmap) { if (bitmap == null) return null; using (var stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Png); stream.Position = 0; var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = stream; bitmapImage.EndInit(); bitmapImage.Freeze(); return bitmapImage; } } - 调用时先验证转换结果:
var bitmapSource = NativeMethods.ToBitmapSource(image); if (Latest_image != null && bitmapSource != null) { Latest_image.Source = bitmapSource; }
- 检查
image对象无效
虽然代码创建了Bitmap对象,但imageData的参数(宽度、高度、像素格式)可能无效,或imageData.Buffer长度不匹配,导致image处于异常状态。
解决:- 验证
imageData.Width、imageData.Height是否为正整数,像素格式是否为系统支持的类型。 - 检查
imageData.Buffer的长度是否符合当前分辨率和像素格式的要求(比如24位色的缓冲区长度应为宽度×高度×3)。
- 验证
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

