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

如何将System.Drawing.Imaging.PixelFormat转换为System.Windows.Media.PixelFormat

Bitmap与WritableBitmap像素格式对应关系及官方参考

官方文档参考

你可以直接查看微软官方文档中两类像素格式的定义:

  • System.Drawing.PixelFormat 枚举:明确每个GDI+像素格式的位结构、通道顺序和用途
  • System.Windows.Media.PixelFormats 类:定义WPF支持的所有像素格式,每个静态属性都有详细的位布局说明

通过对比两者的位布局、通道顺序(比如GDI+的RGB对应WPF的BGR,因字节顺序差异),就能明确对应关系,覆盖所有转换场景。

现有代码的补充说明与完善

你的现有代码覆盖了常见格式,但存在几个需要注意的点:

  1. Format8bppIndexed的转换问题:Indexed格式是带调色板的索引像素,直接转Gray8只有当原Bitmap的调色板是灰度调色板时才正确,如果是彩色调色板,转换后会丢失颜色信息。
  2. 未覆盖的格式:比如Format1bppIndexed、Format4bppIndexed、Format64bppArgb、Format64bppPArgb等格式没有处理。
  3. 缺少默认分支:如果传入未定义的格式,会返回未初始化的变量,引发错误。

完善后的转换代码示例:

private System.Windows.Media.PixelFormat ConvertPixelFormats(System.Drawing.PixelFormat pixelFormat)
{
    return pixelFormat switch
    {
        System.Drawing.PixelFormat.Format16bppRgb555 => System.Windows.Media.PixelFormats.Bgr555,
        System.Drawing.PixelFormat.Format16bppRgb565 => System.Windows.Media.PixelFormats.Bgr565,
        System.Drawing.PixelFormat.Format24bppRgb => System.Windows.Media.PixelFormats.Bgr24,
        System.Drawing.PixelFormat.Format32bppRgb => System.Windows.Media.PixelFormats.Bgr32,
        System.Drawing.PixelFormat.Format32bppPArgb => System.Windows.Media.PixelFormats.Pbgra32,
        System.Drawing.PixelFormat.Format32bppArgb => System.Windows.Media.PixelFormats.Bgra32,
        System.Drawing.PixelFormat.Format8bppIndexed => System.Windows.Media.PixelFormats.Gray8, // 需确保原Bitmap调色板为灰度
        System.Drawing.PixelFormat.Format4bppIndexed => System.Windows.Media.PixelFormats.Gray4, // 仅灰度调色板适用
        System.Drawing.PixelFormat.Format1bppIndexed => System.Windows.Media.PixelFormats.BlackWhite,
        System.Drawing.PixelFormat.Format64bppArgb => System.Windows.Media.PixelFormats.Rgba64,
        System.Drawing.PixelFormat.Format64bppPArgb => System.Windows.Media.PixelFormats.Prgba64,
        _ => throw new ArgumentOutOfRangeException(nameof(pixelFormat), "不支持的像素格式转换")
    };
}

额外注意事项

  • 涉及Indexed格式转换时,必须先检查原Bitmap的Palette是否符合目标格式的要求,否则需要先将Indexed格式转换为RGB类格式再进行转换。
  • GDI+与WPF的像素字节顺序存在差异(GDI+是RGB,WPF是BGR),这也是转换时格式名称对应需要注意的点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:10:33