Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


OpenXML Replace Image
Finds an image on the slide with matching alternate text, and replaces the content.

/// <summary>
/// Replace first image in slide that matches alternate text with the new image
/// </summary>
/// <param name="presentationDocument"></param>
/// <param name="newImagePath"></param>
/// <param name="alternateTextToFind"></param>
/// <param name="slideIndex"></param>
public static void ReplaceFirstImageMatchingAltText(PresentationDocument presentationDocument, string newImagePath, string alternateTextToFind, int slideIndex)
{
OpenXmlElementList slideIds = presentationDocument.PresentationPart.Presentation.SlideIdList.ChildElements;
string relId = (slideIds[slideIndex] as SlideId).RelationshipId; // get first slide
// Get the slide part from the relationship ID.
SlidePart slide = (SlidePart)presentationDocument.PresentationPart.GetPartById(relId);

var pictures = slide.Slide.Descendants<ShapeTree>().First().Descendants<Picture>().ToList();
foreach (var picture in pictures)
{
// get photo desc to see if it matches search text
var nonVisualPictureProperties = picture.Descendants<NonVisualPictureProperties>().FirstOrDefault();
if (nonVisualPictureProperties == null)
continue;
var nonVisualDrawingProperties99 = nonVisualPictureProperties.Descendants<NonVisualDrawingProperties>().FirstOrDefault();
if (nonVisualDrawingProperties99 == null)
continue;
var desc = nonVisualDrawingProperties99.Description;
if (desc == null || desc.Value == null || !desc.Value.Contains(alternateTextToFind))
continue;

BlipFill blipFill = picture.Descendants<BlipFill>().First();
var blip = blipFill.Descendants<Drawing.Blip>().First();
string embedId = blip.Embed; // now we need to find the embedded content and update it.

// find the content
ImagePart imagePart = (ImagePart)slide.GetPartById(embedId);
if (imagePart != null)
{
using (FileStream fileStream = new FileStream(newImagePath, FileMode.Open))
{
imagePart.FeedData(fileStream);
fileStream.Close();
}
return; // found the photo and replaced it.
}
}
}

Created By: amos 4/24/2014 6:24:18 PM