2011-08-21 12 views
6

Esta es una pregunta de seguimiento a How can I retrieve images from a .pptx file using MS Open XML SDK?¿Cómo puedo recuperar algunos datos y formatos de imagen usando MS Open XML SDK?

¿Cómo puedo recuperar:

  • Los datos de imagen de un objeto DocumentFormat.OpenXml.Presentation.Picture?
  • El nombre y/o tipo de la imagen?

en, por ejemplo, los siguientes:

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

Soy consciente de que estoy un poco pidiendo respuestas fuera de la horno-aquí, pero simplemente no puedo encontrar buenos suficientes documentos en cualquier parte para resolverlo por mi cuenta

Respuesta

10

Primero, obtenga una referencia al ImagePart de su imagen. La clase ImagePart proporciona la información que está buscando. Aquí está un ejemplo de código:

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

Por la misma razón también se puede iterar sobre todos los de ImagePart de un SlidePart utilizando el siguiente código:

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

Esperanza, esto ayuda.

Cuestiones relacionadas