Emily C. answered 06/11/25
Computer Science Tutor & University Senior
To dynamically add an image to a PowerPoint presentation using Open XML SDK, you need to:
- Add the image as a part (usually JPEG or PNG) to the presentation.
- Create a reference (relationship) to that image.
- Add a picture element to the slide that uses that image.
Here's a complete C# example to add the photo to a slide:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using A = DocumentFormat.OpenXml.Drawing;
using P = DocumentFormat.OpenXml.Presentation;
using System.IO;
using System.Linq;
public class PowerPointImageAdder
{
public static void AddImageToSlide(string presentationFile, string imagePath, int slideIndex = 0)
{
using (PresentationDocument presentationDoc = PresentationDocument.Open(presentationFile, true))
{
PresentationPart presentationPart = presentationDoc.PresentationPart;
SlidePart slidePart = GetSlidePartByIndex(presentationPart, slideIndex);
// Add image part
ImagePart imagePart = slidePart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(imagePath, FileMode.Open))
{
imagePart.FeedData(stream);
}
string relationshipId = slidePart.GetIdOfPart(imagePart);
// Define picture ID and name
string embedId = relationshipId;
string picName = Path.GetFileName(imagePath);
uint shapeId = 1025U;
// Create the picture
P.Picture picture = new P.Picture(
new P.NonVisualPictureProperties(
new P.NonVisualDrawingProperties() { Id = shapeId, Name = picName },
new P.NonVisualPictureDrawingProperties(new A.PictureLocks() { NoChangeAspect = true }),
new ApplicationNonVisualDrawingProperties()
),
new P.BlipFill(
new A.Blip() { Embed = embedId },
new A.Stretch(new A.FillRectangle())
),
new P.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 1000000L, Y = 1000000L }, // Position (X, Y)
new A.Extents() { Cx = 3000000L, Cy = 3000000L } // Size (width, height)
),
new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }
)
);
// Add to the slide
slidePart.Slide.CommonSlideData.ShapeTree.AppendChild(picture);
// Save the slide
slidePart.Slide.Save();
}
}
// Helper method: get slide part by index
private static SlidePart GetSlidePartByIndex(PresentationPart presentationPart, int slideIndex)
{
var slideIdList = presentationPart.Presentation.SlideIdList;
SlideId slideId = slideIdList.ChildElements[slideIndex] as SlideId;
string relId = slideId.RelationshipId;
return (SlidePart)presentationPart.GetPartById(relId);
}
}