You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI3中如何旋转MediaFrameReader捕获的摄像头图像?

WinUI3 MediaFrameReader 获取的 SoftwareBitmap 旋转解决方案

有效方法:通过 BitmapDecoder 结合 BitmapTransform 旋转

跳过你之前尝试的转码流后出现黑图的错误方式,直接利用BitmapDecoder的变换能力处理SoftwareBitmap,步骤如下:

核心代码实现

// 假设 originalBitmap 是从 MediaFrameReader 获取到的原始图像
SoftwareBitmap rotatedBitmap = null;

// 确保图像格式为 Transform 支持的类型(BGRA8 + Premultiplied Alpha)
if (originalBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || 
    originalBitmap.BitmapAlphaMode != BitmapAlphaMode.Premultiplied)
{
    originalBitmap = SoftwareBitmap.Convert(originalBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
}

// 定义旋转角度(根据摄像头实际方向选择:Clockwise90/180/270Degrees)
var transform = new BitmapTransform
{
    Rotation = BitmapRotation.Clockwise90Degrees
};

// 借助内存流完成变换
using (var ms = new InMemoryRandomAccessStream())
{
    // 将原始图像写入流
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ms);
    encoder.SetSoftwareBitmap(originalBitmap);
    await encoder.FlushAsync();

    ms.Seek(0);
    // 解码时应用旋转变换
    var decoder = await BitmapDecoder.CreateAsync(ms);
    rotatedBitmap = await decoder.GetSoftwareBitmapAsync(
        originalBitmap.BitmapPixelFormat,
        originalBitmap.BitmapAlphaMode,
        transform,
        ExifOrientationMode.IgnoreExifOrientation,
        ColorManagementMode.DoNotColorManage
    );
}

// rotatedBitmap 即为旋转后的图像,可直接用于 OCR 识别

你之前尝试的方法无效原因

  • MediaCapture.SetPreviewRotation:仅对**视频预览流(VideoPreview)**生效,MediaFrameReader 的帧来自独立的 MediaFrameSource,不受该设置影响
  • SetEncodingPropertiesAsync:该方法针对预览/录制的编码参数(分辨率、帧率等),不控制图像旋转,且对 MediaFrameSource 无效
  • 转码流出现黑图:通常是因为原始图像为 YUV 格式,编码时未完成正确的格式转换,导致解码后无有效像素数据

额外提示

  • 可以通过MediaFrameSourceInfo.Properties获取摄像头的物理旋转角度,动态设置BitmapTransform.Rotation,适配不同设备
  • 处理完成后及时释放不再使用的SoftwareBitmap实例,避免内存占用过高

内容的提问来源于stack exchange,提问作者Tobias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:22:38