如何使用MS Open XML SDK检索一些图像数据和格式?

时间:2011-08-21 08:07:06

标签: c# .net image openxml openxml-sdk

这是How can I retrieve images from a .pptx file using MS Open XML SDK?

的后续问题

如何检索:

  • 来自DocumentFormat.OpenXml.Presentation.Picture对象的图像数据?
  • 图片名称和/或类型?

,例如,以下内容:

using (var doc = PresentationDocument.Open(pptx_filename, false)) {
    var presentation = doc.PresentationPart.Presentation;

    foreach (SlideId slide_id in presentation.SlideIdList) {
        SlidePart slide_part = doc.PresentationPart.GetPartById(slide_id.RelationshipId) as SlidePart;
        if (slide_part == null || slide_part.Slide == null)
            continue;
        Slide slide = slide_part.Slide;
        foreach (var pic in slide.Descendants<Picture>()) {
            // how can one obtain the pic format and image data?
        }
    }
}

我意识到我有点要求在这里找到烤箱外的答案,但我无法在任何地方找到足够好的文档来自行解决。

1 个答案:

答案 0 :(得分:10)

首先,获取对Picture的ImagePart的引用。 ImagePart类提供您要查找的信息。这是一个代码示例:

string fileName = @"c:\temp\myppt.pptx";
using (var doc = PresentationDocument.Open(fileName, false))
{        
  var presentation = doc.PresentationPart.Presentation;

  foreach (SlideId slide_id in presentation.SlideIdList)
  {          
    SlidePart slide_part = doc.PresentationPart.GetPartById(slide_id.RelationshipId) as SlidePart;
    if (slide_part == null || slide_part.Slide == null)
      continue;
    Slide slide = slide_part.Slide;

    // from a picture
    foreach (var pic in slide.Descendants<Picture>())
    {                                
      // First, get relationship id of image
      string rId = pic.BlipFill.Blip.Embed.Value;

      ImagePart imagePart = (ImagePart)slide.SlidePart.GetPartById(rId);

     // Get the original file name.
      Console.Out.WriteLine(imagePart.Uri.OriginalString);                        
      // Get the content type (e.g. image/jpeg).
      Console.Out.WriteLine("content-type: {0}", imagePart.ContentType);           

      // GetStream() returns the image data
      System.Drawing.Image img = System.Drawing.Image.FromStream(imagePart.GetStream());

      // You could save the image to disk using the System.Drawing.Image class
      img.Save(@"c:\temp\temp.jpg"); 
    }                    
  }
}

同样,你也可以使用以下代码迭代SlidePart的所有ImagePart:

// iterate over the image parts of the slide part
foreach (var imgPart in slide_part.ImageParts)
{            
  Console.Out.WriteLine("uri: {0}",imgPart.Uri);
  Console.Out.WriteLine("content type: {0}", imgPart.ContentType);                        
}

希望,这有帮助。