Files
XplorePlane/XP.Camera/PixelConverter.cs
T
2026-04-13 14:36:18 +08:00

34 lines
1.3 KiB
C#

using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace XP.Camera;
/// <summary>
/// 提供像素数据到 WPF BitmapSource 的转换工具方法。
/// </summary>
public static class PixelConverter
{
/// <summary>
/// 将原始像素数据转换为 WPF 的 BitmapSource 对象。
/// 返回的 BitmapSource 已调用 Freeze(),可跨线程访问。
/// </summary>
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;
}
}