在 C# 中将 XPS 转换为 BMP
在 C# 中将 XPS 文件转换为 BMP 图像是一个常见需求,当您需要提取 XPS 文档的视觉表示以便打印、归档或集成到图像处理工作流中时。使用 Conholdate.Total for .NET,这个任务变得简单而高效。
为什么将 XPS 转换为 BMP?
这里有一些你可能需要将 XPS 转换为 BMP 的理由:
- 高质量输出:BMP 保留完整的图像保真度,适用于打印或设计工作。
- 简化共享:BMP 图像可以轻松地在各个平台上打开和查看。
- 数据提取:提取页面级内容以进行分析或光学字符识别(OCR)。
- 批处理:使用 .NET 自动化一次性转换多个页面或文档。
在 C# 中将 XPS 转换为 BMP
按照以下步骤进行转换:
- 使用
XpsDocument类加载 XPS 文档。 - 创建并配置
BmpSaveOptions的实例。 - 调用
SaveAsImage方法生成 BMP 图像字节数组。 - 逐页遍历并将图像保存到磁盘。
在 C# 中将 XPS 转换为 BMP
// Define the working directory.
string dataDir = "/Desktop";
string outputFileName = dataDir + "XPStoImage_out.bmp";
// Instantiate an instance of the XpsLoadOptions class.
// Load XPS document from the XPS file by initializing an instance of the XpsDocument class.
XpsDocument document = new XpsDocument(dataDir + "input.xps", new XpsLoadOptions());
// Initialize BmpSaveOptions object with necessary parameters.
BmpSaveOptions options = new BmpSaveOptions()
{
SmoothingMode = SmoothingMode.HighQuality,
Resolution = 300,
PageNumbers = new int[] { 1, 2, 6 }
};
// Invoke SaveAsImage method to save XPS document to the images byte arrays.
byte[][][] imagesBytes = document.SaveAsImage(options);
// Iterate through document partitions (fixed documents, in XPS terms)
for (int i = 0; i < imagesBytes.Length; i++)
{
// Iterate through partition pages
for (int j = 0; j < imagesBytes[i].Length; j++)
{
// Initialize image output stream
using (Stream imageStream = System.IO.File.Open(Path.GetDirectoryName(outputFileName) + Path.DirectorySeparatorChar +
Path.GetFileNameWithoutExtension(outputFileName) + "_" + (i + 1) + "_" + (j + 1) +
Path.GetExtension(outputFileName), System.IO.FileMode.Create, System.IO.FileAccess.Write))
// Write image
imageStream.Write(imagesBytes[i][j], 0, imagesBytes[i][j].Length);
}
}
此代码演示了在 C# 中将 XPS 文档转换为 BMP 图像的完整过程。使用 XpsDocument 类及 XpsLoadOptions 加载 XPS 文件,以便为渲染做好准备。然后,初始化一个 BmpSaveOptions 对象,您可以在其中设置图像分辨率、平滑模式和要转换的特定页面。这确保每一页都被单独保存,并且有清晰的标签,使管理和在后续应用中使用生成的图像变得容易。总体而言,这种方法提供了一种高效的方式来提取和保存 XPS 内容为 BMP 格式。
结论
在 C# 中将 XPS 文档转换为 BMP 图像允许开发人员生成光栅化图像输出,以便于集成、归档或进一步处理。 Conholdate.Total for .NET 提供强大的 API,以最小的努力处理此类文档转换。
