对于许多处理 Word 文档的开发人员来说,处理 DOCX 文件中嵌入的图像是一项至关重要的任务。无论是处理报告、提取视觉数据还是自动迁移内容,能够使用 C# 从 DOCX 中提取图像都可以显著增强应用程序的功能。使用正确的方法和解析器库,开发人员可以有效地从 DOCX 文件中检索嵌入的图像。在本文中,我们将引导您完成该过程并提供 C# 代码以从 DOCX 中提取图像,从而轻松地在您的项目中实现此功能。
使用 C# 从 DOCX 中提取图像的步骤
- 通过 NuGet 将 GroupDocs.Parser for .NET 库添加到您的 C# 项目,以便从 DOCX 文件中提取图像
- 通过将 DOCX 文件路径传递给其构造函数来创建 Parser 对象以加载文档
- 调用 Parser.GetImages 来检索 DOCX 文件中嵌入的图像
- 检查图像集合是否不为空,以确保图像可供提取
- 循环遍历集合,提取图像细节,并将图像保存到所需位置
要使用 C# 读取和提取 DOCX 图像,开发人员可以通过几个简单的步骤将此功能无缝集成到他们的应用程序中。无论是用于构建文档处理工具、分析视觉数据还是自动迁移内容,从 DOCX 文件中提取图像的能力都是一项有价值的功能。此过程可帮助开发人员轻松将其应用于各种工作流程,从而使文档管理和分析更加有效。通过遵循提供的步骤,您可以简化提取过程并增强应用程序的功能。
使用 C# 从 DOCX 中提取图像的代码
using System; | |
using GroupDocs.Parser; | |
using GroupDocs.Parser.Data; | |
using System.Collections.Generic; | |
namespace ExtractImagesfromDOCXusingCSharp | |
{ | |
internal class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Apply the license to remove the restrictions imposed by the Parser library | |
License lic = new License(); | |
lic.SetLicense(@"GroupDocs.Parser.lic"); | |
int i = 1; | |
// Create an instance of the Parser class to access its methods | |
// and properties for data processing or manipulation. | |
using (Parser parser = new Parser("input.docx")) | |
{ | |
// Extract images from DOCX | |
IEnumerable<PageImageArea> images = parser.GetImages(); | |
// Check if images extraction is supported | |
if (images == null) | |
{ | |
Console.WriteLine("Images extraction isn't supported"); | |
return; | |
} | |
// Iterate over images | |
foreach (PageImageArea image in images) | |
{ | |
// Print a page index, rectangle and image type: | |
Console.WriteLine(string.Format("Page: {0}, R: {1}, Type: {2}", | |
image.Page.Index, image.Rectangle, image.FileType)); | |
// Save the document to disk | |
image.Save("image" + i++ + image.FileType.Extension); | |
} | |
} | |
} | |
} | |
} |
总之,DOCX 图像提取 C# 教程 表明这个过程简单而有效。该解决方案与平台无关,这意味着上述 C# 代码将在不同的操作系统(如 Windows、macOS 和 Linux)上无缝运行。这确保开发人员不受任何特定操作系统的束缚,使该方法既通用又可靠。对于希望为其应用程序添加图像提取功能的开发人员来说,这是一种可靠的方法。
我们之前发布过一篇使用 C# 从 ODT 文件中提取图像的指南。如需全面的分步教程,请务必查看我们的完整指南,了解如何 使用 C# 从 ODT 中提取图像。