【发布时间】:2018-12-30 20:50:08
【问题描述】:
The answer here 不会替换位图,而是添加位图。有没有办法替换图片中的位图?
使用 PowerPoint COM 互操作(不是 VSTO)。
代码是:
/// <summary>
/// Create or update a picture (bitmap) tag.
/// </summary>
private static PowerPointTagLocation CreateOrUpdatePictureTag(PowerPointTagLocation tagLoc, bool isUpdate, Image picture,
string text, Slide slide)
{
// get a unique name for the picture
string name = FileUtils.MakeValidFileName("wr_bitmap", true) + rand.Next(9999);
// we need a physical file as the bitmap to display.
string filename = name + ".png";
filename = Path.Combine(Path.GetTempPath(), filename);
if (File.Exists(filename))
{
Trap.trap();
File.Delete(filename);
}
// if it's an update for a picture, we just update the AlternativeText.
// And the bitmap if we get it.
if (isUpdate && tagLoc.IsPicture) {
tagLoc.TagShape.AlternativeText = text;
if (picture != null) {
picture.Save(filename, ImageFormat.Png);
tagLoc.TagShape.Fill.UserPicture(filename);
File.Delete(filename);
}
return tagLoc;
}
if (picture == null)
CommonBitmaps.photo_scenery.Save(filename, ImageFormat.Png);
else
picture.Save(filename, ImageFormat.Png);
Shape shape;
using (Bitmap bitmap = new Bitmap(filename)) {
PictHandler.GetPictureSize(tagLoc.Tag, bitmap, 0, out var width, out var height);
// position/extent in points. Place in middle of slide
float x, y;
try
{
PageSetup page = ((Presentation)slide.Parent).PageSetup;
x = (page.SlideWidth - (width / 20f)) / 2f;
y = (page.SlideHeight - (height / 20f)) / 2f;
}
catch (Exception) {
x = y = 0;
}
shape = slide.Shapes.AddPicture(filename, MsoTriState.msoFalse, MsoTriState.msoTrue, x, y, width / 20f, height / 20f);
// set select
shape.AlternativeText = text;
shape.Name = name;
}
// copy properties across
// if (copyPicture)
// pic.AssignProperties(tagLoc.TagRange.Picture);
// delete the old picture as we wrote a new one.
if (isUpdate)
tagLoc.Delete();
// delete the temp file
File.Delete(filename);
return new PowerPointTagLocation(tagLoc.Tag, shape);
}
【问题讨论】:
-
您链接到的答案应该替换幻灯片上的现有图片,而不是添加到其中。如果您发布代码,它可能有助于理解您遇到的问题。
-
@SteveRindsberg - 我已经添加了代码。如果有任何不清楚的地方,请告诉我。谢谢 - 戴夫
-
在我看来,您的代码是在添加新图片,而不是更改现有形状的图片填充(如您在上面链接到的代码中)...参见 shape = slide.Shapes。添加图片
-
@SteveRindsberg if "isUpdate == true" 那么它正在调用:tagLoc.TagShape.Fill.UserPicture(filename);这不应该覆盖位图吗? (对于“isUpdate == false”,是的,然后它会创建一张新图片。)
-
谢谢;我是 VB/VBA 用户,所以不熟悉这里的语法。但是,是的,UserPicture(Filename) 应该用所需的文件名填充形状。