图片和文字是word文档中两种最常见的对象,在微软word中,如果我们想要提取出一个文档内的图片,
只需要右击图片选择另存为然后命名保存就可以了,今天这篇文章主要是实现如何使用C#从word文档中提取图片。
这里我准备了一个含有文字和图片的word文档:
详细步骤与代码:
步骤1 : 添加引用。
新建一个Visual C#控制台项目,添加引用并使用如下命名空间:
- using System;
- using Spire.Doc;
- using Spire.Doc.Documents;
- using Spire.Doc.Fields;
复制代码
步骤2 : 新建一个word文档对象并加载需要提取图片的word文档。
Document document = new Document("法国景点.docx ");
步骤3 : 遍历文档中的所有section,找到图片,将它们提取出来并保存。
- int index = 0;
- //获取文档的section
- foreach (Section section in document.Sections)
- {
- //获取section中的段落
- foreach (Paragraph paragraph in section.Paragraphs)
- {
- //获取段落中的文档对象
- foreach (DocumentObject docObject in paragraph.ChildObjects)
- {
- //对对象的type进行判断,如果是图片,就提取出来
- if (docObject.DocumentObjectType == DocumentObjectType.Picture)
- {
- DocPicture picture = docObject as DocPicture;
- //给图片命名
- String imageName = String.Format(@"images\Image-{0}.png", index);
- //保存图片
- picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
- index++;
复制代码
提取出来的图片:
全部代码:
- using System;
- using Spire.Doc;
- using Spire.Doc.Documents;
- using Spire.Doc.Fields;
- using System.Drawing;
- namespace Extract_image_from_word
- {
- class Program
- {
- static void Main(string[] args)
- {
- Document document = new Document("法国景点.docx");
- int index = 0;
- foreach (Section section in document.Sections)
- {
- foreach (Paragraph paragraph in section.Paragraphs)
- {
- foreach (DocumentObject docObject in paragraph.ChildObjects)
- {
- if (docObject.DocumentObjectType == DocumentObjectType.Picture)
- {
- DocPicture picture = docObject as DocPicture;
- String imageName = String.Format(@"images\Image-{0}.png", index);
- picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
- index++;
- }
- }
- }
- }
- }
- }
- }
复制代码
|