替换PPT文档中的图片

2025-10-16 11:32:44

1、下载并安装Spire.Presentation for .NET, 并将Spire.Presentation.dll文件引用到项目中。

2、将代码放入Visual Studio中:

【C#】

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Spire.Presentation;

using Spire.Presentation.Drawing;

using System.Drawing;

namespace Replace_Image2

{   

    class Program   

        {      

             static void Main(string[] args)       

                  {           

                     //创建Presentation实例           

                     Presentation ppt = new Presentation();           

                     //加载PowerPoint文档           

                     ppt.LoadFromFile("Input.pptx");           

                     //获取第一张幻灯片          

                     ISlide slide = ppt.Slides[0];           

                     //添加一张新图片,用于替换指定的图片          

                     IImageData image = ppt.Images.Append(Image.FromFile("image2.jpg"));           

                     //遍历幻灯片中的形状           

                     foreach (IShape shape in slide.Shapes)           

                     {               

                       //判断形状是否是图片               

                       if (shape is SlidePicture)               

                           {                   

                             //判断图片的标题                   

                             if (shape.AlternativeTitle == "image1")                   

                                {                                

                                   //使用新图片替换标题为“image1”的图片                                                   (shape as SlidePicture).PictureFill.Picture.EmbedImage = image;                  

                                  }               

                             }           

                     }           

                      //保存文件           

                     ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);       

           }   

     }

}

3、调试并运行代码后,生成的文档如下图所示:

替换PPT文档中的图片

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢