圖片和文字是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;//獲取文檔的sectionforeach (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 組件,它除了可以從文檔中提取圖片,還可以提取文本,這里我只寫了提取圖片的,提取文本的也差不多,如有需要可以留言。
新聞熱點
疑難解答