从Docx中提取图像

时间:2013-09-04 12:22:12

标签: c# openxml docx

我正在尝试从docx文件导出图像。 如何将Shape对象中的编码包转换为图像?

我的代码示例:

DocumentFormat.OpenXml.Vml.Shape shape = imageElement.Descendants<DocumentFormat.OpenXml.Vml.Shape>().FirstOrDefault();
byte[] bytes = System.Convert.FromBase64String(shape.EncodedPackage.Value.Replace("\n", ""));
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
   image = System.Drawing.Image.FromStream(ms);
}
image.Save(fileName);

1 个答案:

答案 0 :(得分:0)

您可以从ImagePart获取图片。试试这个:

var imageParts = doc.MainDocumentPart.ImageParts;
foreach (var imagePart in imageParts)
{
      var uri = imagePart.Uri;
      var filename = uri.ToString().Split('/').Last();
      var stream = doc.Package.GetPart(uri).GetStream();

       Bitmap b = new Bitmap(stream);
       b.Save(@"C:\Extracted_Images\" + filename);
}