本指南中的解决方案演示了如何从现有 Word 文档中提取图像,欢迎查阅!
本指南中的解决方案演示了如何从现有 Word 文档中提取图像,并通过Spire.Doc for .NET将它们保存到 C# 和 VB.NET 中的指定路径。
图像是属于段落项的一种文档对象。Spire.Doc for .NET 提供了一个DocumentObject类来将图像存储在 Document 中。并且还提供了一个DocPicture类来获取和设置文档的图像。下载并安装 Spire.Doc for .NET。按照步骤从 Word 中提取图像。
- 获取文档中每个部分的每个段落。
- 获取 Paragraph 中 ChildObjects 的每个 DocumentObject。
- 如果获取的 DocumentObjectType 为 Picture,则初始化一个 DocPicture 类实例,并将 DocumentObject 赋值为该实例的值。
- 通过调用 String.Format(String format, object arg0) 初始化 String 类实例以命名提取的图像而不是其原始名称
- 调用 DocPictrue.Image.Save(String, ImageFormat) 方法保存图像。
【C#】
using Spire.Doc;using Spire.Doc.Documents;using Spire.Doc.Fields;using System;namespace ExtractImage{class Program{static void Main(string[] args){//Load documentDocument document = new Document(@"E:WorkDocumentsWordDocumentsSpire.Doc for .NET.docx");int index = 0;//Get Each Section of Documentforeach (Section section in document.Sections){//Get Each Paragraph of Sectionforeach (Paragraph paragraph in section.Paragraphs){//Get Each Document Object of Paragraph Itemsforeach (DocumentObject docObject in paragraph.ChildObjects){//If Type of Document Object is Picture, Extract.if (docObject.DocumentObjectType == DocumentObjectType.Picture){DocPicture picture = docObject as DocPicture;//Name ImageString imageName = String.Format(@"imagesImage-{0}.png", index);//Save Imagepicture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);index++;}}}}}}}
【VB.NET】
Imports Spire.DocImports Spire.Doc.DocumentsImports Spire.Doc.FieldsNamespace ExtractImageClass ProgramPrivate Shared Sub Main(args As String())'Load documentDim document As New Document("E:WorkDocumentsWordDocumentsSpire.Doc for .NET.docx")Dim index As Integer = 0'Get Each Section of DocumentFor Each section As Section In document.Sections'Get Each Paragraph of SectionFor Each paragraph As Paragraph In section.Paragraphs'Get Each Document Object of Paragraph ItemsFor Each docObject As DocumentObject In paragraph.ChildObjects'If Type of Document Object is Picture, Extract.If docObject.DocumentObjectType = DocumentObjectType.Picture ThenDim picture As DocPicture = TryCast(docObject, DocPicture)'Name ImageDim imageName As [String] = [String].Format("imagesImage-{0}.png", index)'Save Imagepicture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png)index += 1End IfNextNextNextEnd SubEnd ClassEnd Namespace
调试后,所有提取的图像都保存在指定路径中。打开目录,就会找到图片。

以上便是如何在 Word 中插入图像(C#/VB.NET),如果您有其他问题也可以继续浏览本系列文章,获取相关教程,你还可以给我留言或者加入我们的官方技术交流群。
欢迎下载|体验更多E-iceblue产品
获取更多信息请咨询在线客服 ;
标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!