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

前端之家收集整理的这篇文章主要介绍了c# – 如何使用MS Open XML 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?
        }
    }
}

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

解决方法

首先,获取对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);                        
}

希望这可以帮助.

原文链接:https://www.f2er.com/csharp/243640.html

猜你在找的C#相关文章