【问题标题】:How can I retrieve some image data and format using MS Open XML SDK?如何使用 MS Open XML SDK 检索一些图像数据和格式?
【发布时间】:2011-08-21 08:07:05
【问题描述】:
这是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?
}
}
}
我意识到我在这里有点要求不切实际的答案,但我无法在任何地方找到足够好的文档来自己解决。
【问题讨论】:
标签:
c#
.net
image
openxml
openxml-sdk
【解决方案1】:
首先,获取对图片的 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);
}
希望,这会有所帮助。