电脑疯子技术论坛|电脑极客社区

微信扫一扫 分享朋友圈

已有 1888 人浏览分享

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

[复制链接]
1888 0
图片和文字是word文档中两种最常见的对象,在微软word中,如果我们想要提取出一个文档内的图片,

只需要右击图片选择另存为然后命名保存就可以了,今天这篇文章主要是实现如何使用C#从word文档中提取图片。

这里我准备了一个含有文字和图片的word文档:


详细步骤与代码:

步骤1 : 添加引用

新建一个Visual C#控制台项目,添加引用并使用如下命名空间:

  1. using System;
  2. using Spire.Doc;
  3. using Spire.Doc.Documents;
  4. using Spire.Doc.Fields;
复制代码


步骤2 : 新建一个word文档对象并加载需要提取图片的word文档。

Document document = new Document("法国景点.docx ");

步骤3 : 遍历文档中的所有section,找到图片,将它们提取出来并保存。



  1. int index = 0;
  2. //获取文档的section
  3. foreach (Section section in document.Sections)
  4. {
  5. //获取section中的段落
  6. foreach (Paragraph paragraph in section.Paragraphs)
  7. {
  8. //获取段落中的文档对象
  9. foreach (DocumentObject docObject in paragraph.ChildObjects)
  10. {
  11. //对对象的type进行判断,如果是图片,就提取出来
  12. if (docObject.DocumentObjectType == DocumentObjectType.Picture)
  13. {
  14. DocPicture picture = docObject as DocPicture;
  15. //给图片命名
  16. String imageName = String.Format(@"images\Image-{0}.png", index);
  17. //保存图片
  18. picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
  19. index++;
复制代码


提取出来的图片:


全部代码:


  1. using System;
  2. using Spire.Doc;
  3. using Spire.Doc.Documents;
  4. using Spire.Doc.Fields;
  5. using System.Drawing;
  6. namespace Extract_image_from_word
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Document document = new Document("法国景点.docx");
  13. int index = 0;
  14. foreach (Section section in document.Sections)
  15. {
  16. foreach (Paragraph paragraph in section.Paragraphs)
  17. {
  18. foreach (DocumentObject docObject in paragraph.ChildObjects)
  19. {
  20. if (docObject.DocumentObjectType == DocumentObjectType.Picture)
  21. {
  22. DocPicture picture = docObject as DocPicture;
  23. String imageName = String.Format(@"images\Image-{0}.png", index);
  24. picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
  25. index++;
  26. }
  27. }
  28. }
  29. }
  30. }
  31. }
  32. }
复制代码






您需要登录后才可以回帖 登录 | 注册

本版积分规则

1

关注

0

粉丝

9021

主题
精彩推荐
热门资讯
网友晒图
图文推荐

Powered by Pcgho! X3.4

© 2008-2022 Pcgho Inc.