这篇文章将介绍如何使用 Spire.Presentation for Java 组件插入图片到 PowerPoint 文档以及提取 PowerPoint 文档中的图片。
插入图片到 PowerPoint 文档
import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import java.awt.geom.Rectangle2D;
public class InsertImages {
public static void main(String[] args) throws Exception {
//创建Presentation实例
Presentation ppt = new Presentation();
Rectangle2D rect = new Rectangle2D.Double(ppt.getSlideSize().getSize().getWidth() / 2 - 280, 140, 120, 120);
//获取第一张幻灯片(创建后默认含有一张幻灯片)
ISlide slide = ppt.getSlides().get(0);
//插入图片到幻灯片
IEmbedImage image = slide.getShapes().appendEmbedImage(ShapeType.RECTANGLE, "a.jpg", rect);
image.getLine().setFillType(FillFormatType.NONE);
//添加一张新的幻灯片
slide = ppt.getSlides().append();
//插入图片到幻灯片
image = slide.getShapes().appendEmbedImage(ShapeType.RECTANGLE, "b.jpg", rect);
image.getLine().setFillType(FillFormatType.NONE);
//保存文档
ppt.saveToFile("InsertImages.pptx", FileFormat.PPTX_2013);
}
}
提取 PowerPoint文档中的图片
Spire.Presentation for Java 支持提 取PowerPoint 文档中的所有图片,也支持提取指定幻灯片中的图片。
以下示例展示了如何提取 PowerPoint 文档中的所有图片:
import com.spire.presentation.Presentation;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class ExtractImages {
public static void main(String[] args) throws Exception {
//创建Presentation实例
Presentation ppt = new Presentation();
//加载PowerPoint文档
ppt.loadFromFile("InsertImages.pptx");
//提取文档中的所有图片
for (int i = 0; i < ppt.getImages().getCount(); i++) {
BufferedImage image = ppt.getImages().get(i).getImage();
ImageIO.write(image, "PNG", new File(String.format("presentation/" + "extractImage-%1$s.png", i)));
}
}
}
以下示例展示了如何提取指定幻灯片中的图片:
import com.spire.presentation.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class ExtractImages {
public static void main(String[] args) throws Exception {
//创建Presentation实例
Presentation ppt = new Presentation();
//加载PowerPoint文档
ppt.loadFromFile("InsertImages.pptx");
//获取第一张幻灯片
ISlide slide = ppt.getSlides().get(0);
//提取图片
for(int i = 0; i< slide.getShapes().getCount(); i++)
{
IShape shape = slide.getShapes().get(i);
if(shape instanceof SlidePicture)
{
SlidePicture pic = (SlidePicture) shape;
BufferedImage image = pic.getPictureFill().getPicture().getEmbedImage().getImage();
ImageIO.write(image, "PNG", new File(String.format("slide/" + "extractImage-%1$s.png", i)));
}
if(shape instanceof PictureShape)
{
PictureShape ps = (PictureShape) shape;
BufferedImage image = ps.getEmbedImage().getImage();
ImageIO.write(image, "PNG", new File(String.format("slide/" + "extractImage-%1$s.png", i)));
}
}
}
}