user610650
user610650

Reputation:

How can I retrieve some image data and format using MS Open XML SDK?

This is a follow-up question to How can I retrieve images from a .pptx file using MS Open XML SDK?

How can I retrieve:

in, say, the following:

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?
        }
    }
}

I realize that I'm kinda asking for out-of-the-oven answers here, but I just can't find good enough docs anywhere to figure it out on my own.

Upvotes: 6

Views: 4985

Answers (1)

Hans
Hans

Reputation: 13040

First, obtain a reference to the ImagePart of your Picture. The ImagePart class provides the information you are looking for. Here is a code sample:

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"); 
    }                    
  }
}

By the same token you could also iterate over all ImagePart's of a SlidePart using the following code:

// 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);                        
}

Hope, this helps.

Upvotes: 11

Related Questions