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

能否在.NET 6控制台应用中创建多页TIFF及使用BitmapSource等类?

在.NET 6控制台应用中创建多页TIFF并使用BitmapSource、TiffBitmapEncoder

可以在.NET 6控制台应用中使用BitmapSource、TiffBitmapEncoder等类,无需回退到.NET Framework 4.8。这些类属于WPF组件,默认不会被控制台项目引用,只需手动添加相关依赖即可。

操作步骤

  1. 添加WPF框架引用
    在项目的.csproj文件中添加以下框架引用,直接引入WPF相关组件:

    <ItemGroup>
      <FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
    </ItemGroup>
    

    也可以通过NuGet包管理器安装System.Windows.Extensions包,不过框架引用的方式更直接高效。

  2. 编写多页TIFF生成代码
    以下是完整的示例代码,用于创建包含多页的TIFF文件:

    using System.IO;
    using System.Windows.Media.Imaging;
    using System.Windows.Media;
    
    class Program
    {
        static void Main(string[] args)
        {
            // 创建测试用的BitmapSource页面
            var page1 = GenerateTestBitmap(300, 300, Colors.Coral);
            var page2 = GenerateTestBitmap(300, 300, Colors.SkyBlue);
            var page3 = GenerateTestBitmap(300, 300, Colors.LimeGreen);
    
            // 初始化TIFF编码器
            var tiffEncoder = new TiffBitmapEncoder();
            tiffEncoder.Compression = TiffCompressOption.Zip; // 可选压缩方式
    
            // 将所有页面添加到编码器
            tiffEncoder.Frames.Add(BitmapFrame.Create(page1));
            tiffEncoder.Frames.Add(BitmapFrame.Create(page2));
            tiffEncoder.Frames.Add(BitmapFrame.Create(page3));
    
            // 保存多页TIFF到文件
            using var fileStream = new FileStream("multi-page-output.tiff", FileMode.Create);
            tiffEncoder.Save(fileStream);
        }
    
        // 辅助方法:生成指定尺寸和颜色的BitmapSource
        static BitmapSource GenerateTestBitmap(int width, int height, Color fillColor)
        {
            var pixelData = new byte[width * height * 4]; // BGRA像素格式
            for (int i = 0; i < pixelData.Length; i += 4)
            {
                pixelData[i] = fillColor.B;
                pixelData[i + 1] = fillColor.G;
                pixelData[i + 2] = fillColor.R;
                pixelData[i + 3] = 255; // 完全不透明
            }
    
            return BitmapSource.Create(
                width, height,
                96, 96, // 水平/垂直DPI
                PixelFormats.Bgra32,
                null,
                pixelData,
                width * 4); // 每行字节数
        }
    }
    

注意事项

  • 这些WPF组件仅支持Windows平台,如果需要跨平台(Linux/macOS)生成多页TIFF,可以考虑使用第三方库如ImageSharp或Magick.NET。
  • 可以通过修改TiffCompressOption来设置TIFF的压缩方式,比如None、Zip、CCITT4等,根据文件大小和质量需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:27:13