在这篇简短的操作方法文章中,我们将讨论从 C# 中的 Word 文档中提取图像的详细过程。我们将使用 DOCX 作为获取图像的输入文件。但是,您也可以提供 DOC 格式的文档,用于使用 C# 语言提取图像。此外,我们将创建一个工作示例来向您展示如何使用 C# 从 Word 文件中获取图像。
在 C# 中从 Word 文档中提取图像的步骤
- 在 .NET 项目中从 NuGet 网站安装 GroupDocs.Parser for .NET 包以从 Word 文档中提取图像
- 添加必要命名空间的引用,以便从 Word 文件中提取图像
- 实例化 Parser 类以加载输入 DOCX 文档
- 调用 Parser 类的 GetImages 方法从 Word 文档中收集图像
- 遍历图像集合并获取图像的大小、类型和内容
在以上几点中,我们已经解释了创建使用 C#* 从 Word 文档中提取所有图像的功能的每个步骤。在从 NuGet 包管理器配置所需的包并在代码中包含所需的命名空间之后,您必须通过初始化 Parser 类来加载源 Word 文件。之后,GetImages 使您能够收集图像对象,然后您可以遍历该集合以显示图像数据。
在 C# 中从 Word 文档中提取图像的代码
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
using System.IO; | |
using GroupDocs.Parser; | |
using GroupDocs.Parser.Data; | |
namespace ExtractImagesFromWordDocumentInCSharp | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) // Main function to extract images from word using C# | |
{ | |
// Remove the watermark in output | |
string licensePath = "GroupDocs.Parser.lic"; | |
GroupDocs.Parser.License lic = new GroupDocs.Parser.License(); | |
lic.SetLicense(licensePath); | |
// Create an instance of Parser class | |
using (Parser parser = new Parser("sample.docx")) | |
{ | |
// Extract images | |
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)); | |
} | |
} | |
} | |
} | |
} |
在前面的代码片段中,开发了来自 Word* 应用程序的 *C# 图像提取器来演示此功能的工作原理。我们不使用任何第三方工具来提取图像。此示例可以根据您的特定要求进一步增强,您还可以在 Windows、macOS 和 Linux 等任何操作系统上使用此示例。
我们已经讨论了在 C# 中从 Word 文档中提取图像的过程,并在这篇文章中开发了一个示例代码。最近,我们发表了一篇使用 C# 从 Word 文档中提取文本的文章,请查看 如何使用 C# 从 Word 文档中提取文本 指南了解更多信息。