using System.IO; using System.Windows.Media.Imaging; namespace SHH.CameraDashboard; /// /// [UI层] 图像数据转换助手 /// 职责:将内存中的二进制 JPEG 数据高效转换为 WPF 可用的 BitmapImage /// 优化:使用 OnLoad 缓存策略和 Freeze 冻结对象,支持跨线程访问,防止内存泄漏 /// public static class BitmapHelper { public static BitmapImage? ToBitmapImage(byte[] blob) { if (blob == null || blob.Length == 0) return null; try { using (var stream = new MemoryStream(blob)) { var bitmap = new BitmapImage(); bitmap.BeginInit(); // 关键优化 1: 立即加载流到内存,允许 stream 在方法结束后被释放 bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = stream; // 关键优化 2: 忽略内嵌的色彩配置和缩略图,提升解码速度 bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.IgnoreImageCache; bitmap.EndInit(); // 关键优化 3: 冻结对象,使其变得线程安全(可以跨线程传递给 UI) bitmap.Freeze(); return bitmap; } } catch { // 解码失败(可能是坏帧),返回 null 忽略该帧 return null; } } }