好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

如何使用C#从word文档中提取图片

图片和文字是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++;

}

}

}

}

}

}

}

总结:

这里我使用的是E-iceblue公司的免费 word 组件,它除了可以从文档中提取图片,还可以提取文本,这里我只写了提取图片的,提取文本的也差不多,如有需要可以留言。

dy("nrwz");

查看更多关于如何使用C#从word文档中提取图片的详细内容...

  阅读:70次