在演示文稿中处理图像 — Aspose.Slides FOSS for .NET
Aspose.Slides FOSS for .NET 允许您将图像嵌入演示文稿的共享图像集合,并使用 PictureFrame 形状在幻灯片上显示它们。图像还可以通过 FillType.Picture 用作形状的背景填充。
从文件添加图像
从磁盘加载图像字节并使用 prs.Images.AddImage() 将其添加到演示文稿的图像集合中。然后将图像作为 PictureFrame 放置在幻灯片上:
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
// Add the image to the shared collection
var imageData = File.ReadAllBytes("logo.png");
var img = prs.Images.AddImage(imageData);
// Place it on the slide as a PictureFrame
var slide = prs.Slides[0];
slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 50, 50, 300, 200, img);
prs.Save("with-image.pptx", SaveFormat.Pptx);AddPictureFrame() 的四个位置参数是:x, y, width, height(以点为单位)。
从流添加图像
如果您拥有来自流的图像数据(例如,从 URL 下载或从数据库读取),请直接将其传递给 AddImage():
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
using var stream = File.OpenRead("photo.jpg");
var img = prs.Images.AddImage(stream);
prs.Slides[0].Shapes.AddPictureFrame(ShapeType.Rectangle, 100, 80, 400, 250, img);
prs.Save("from-stream.pptx", SaveFormat.Pptx);对 PictureFrame 的定位和尺寸设置
PictureFrame 由 AddPictureFrame() 返回,继承所有 Shape 几何属性,并且可以在创建后重新定位:
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
var imageData = File.ReadAllBytes("photo.jpg");
var img = prs.Images.AddImage(imageData);
var pf = prs.Slides[0].Shapes.AddPictureFrame(ShapeType.Rectangle, 0, 0, 100, 100, img);
// Reposition and resize after creation
pf.X = 50;
pf.Y = 100;
pf.Width = 350;
pf.Height = 250;
prs.Save("positioned.pptx", SaveFormat.Pptx);使用图像作为形状填充
任何形状(不仅限于 PictureFrame)都可以使用图像作为其背景填充。设置 FillType = FillType.Picture 并将图像分配给 PictureFillFormat.Picture.Image:
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
var imageData = File.ReadAllBytes("background.png");
var img = prs.Images.AddImage(imageData);
var slide = prs.Slides[0];
var shape = slide.Shapes.AddAutoShape(ShapeType.RoundCornerRectangle, 50, 50, 400, 250);
shape.FillFormat.FillType = FillType.Picture;
shape.FillFormat.PictureFillFormat.PictureFillMode = PictureFillMode.Stretch;
shape.FillFormat.PictureFillFormat.Picture.Image = img;
prs.Save("picture-fill.pptx", SaveFormat.Pptx);PictureFillMode.Stretch 将图像缩放以填满整个形状。
在幻灯片中添加多个图像
添加到 prs.Images 的图像在所有幻灯片之间共享。同一图像对象可在多个幻灯片上使用,而无需复制数据:
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
var logoData = File.ReadAllBytes("logo.png");
var logo = prs.Images.AddImage(logoData);
// Add the same image to the first slide
prs.Slides[0].Shapes.AddPictureFrame(ShapeType.Rectangle, 600, 10, 100, 40, logo);
prs.Save("shared-image.pptx", SaveFormat.Pptx);