在Java编程中,如何将图片添加到PPT幻灯片中?
注意:需要访问网址:http://poi.apache.org/download.html , 下载一个Apache POI软件包。这里下载最新版本:poi-bin-3.17-20170915.tar.gz解压并全部导入 。
需要导入全部包,如下图所示 -
以下是使用Java将图片添加到PPT幻灯片中的程序。
package com.yiibai;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
public class AddingImageToPPT {
public static void main(String args[]) throws IOException {
// creating a presentation
XMLSlideShow ppt = new XMLSlideShow();
// creating a slide in it
XSLFSlide slide = ppt.createSlide();
// reading an image
File image = new File("dog.jpg");
// converting it into a byte array
byte[] picture = IOUtils.toByteArray(new FileInputStream(image));
// adding the image to the presentation
XSLFPictureData idx = ppt.addPicture(picture, PictureData.PictureType.PNG);
// creating a slide with given picture on it
XSLFPictureShape pic = slide.createPicture(idx);
// creating a file object
File file = new File("AddingimageToPPT.pptx");
FileOutputStream out = new FileOutputStream(file);
// saving the changes to a file
ppt.write(out);
System.out.println("image added successfully");
out.close();
}
}
执行上面示例代码,得到以下结果 -
image added successfully
这就创建一个PPT文件:AddingimageToPPT.pptx了。