在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了。