using System.Windows.Media; using System.Windows.Media.Imaging; namespace XP.Camera; /// /// 提供像素数据到 WPF BitmapSource 的转换工具方法。 /// public static class PixelConverter { /// /// 将原始像素数据转换为 WPF 的 BitmapSource 对象。 /// 返回的 BitmapSource 已调用 Freeze(),可跨线程访问。 /// public static BitmapSource ToBitmapSource(byte[] pixelData, int width, int height, string pixelFormat) { ArgumentNullException.ThrowIfNull(pixelData); if (width <= 0) throw new ArgumentException("Width must be a positive integer.", nameof(width)); if (height <= 0) throw new ArgumentException("Height must be a positive integer.", nameof(height)); ArgumentNullException.ThrowIfNull(pixelFormat); var (format, stride) = pixelFormat switch { "Mono8" => (PixelFormats.Gray8, width), "BGR8" => (PixelFormats.Bgr24, width * 3), "BGRA8" => (PixelFormats.Bgra32, width * 4), _ => throw new NotSupportedException($"Pixel format '{pixelFormat}' is not supported.") }; var bitmap = BitmapSource.Create(width, height, 96, 96, format, null, pixelData, stride); bitmap.Freeze(); return bitmap; } }