不废话,直接上代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hslf.usermodel.HSLFPictureData;
import org.apache.poi.hslf.usermodel.HSLFPictureShape;
import org.apache.poi.hslf.usermodel.HSLFShape;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
public class PPTImageCompress {
public static void main(String[] args) throws IOException {
// 读取ppt
FileInputStream is = new FileInputStream(new File("D:\\test.ppt"));
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
// 保存图片ppi
int defaultPpi = ppt.getSlideMasters()[0].getApplicationData().getPointsPerInch();
// 设置ppi
int newPpi = 200;
ppt.getSlideMasters()[0].getApplicationData().setPointsPerInch(newPpi);
// 获取所有ppt图片
HSLFPictureData[] pictures = ppt.getPictureData();
// 遍历每一张图片
for (HSLFPictureData picture : pictures) {
// 图片类型
PictureType type = picture.getType();
// 图片后缀
String ext = type.extension;
// 图片数据
byte[] data = picture.getData();
// 创建图片文件
FileOutputStream out = new FileOutputStream("D:\\test\\" + picture.getIndex() + ext);
out.write(data);
out.close();
}
// 遍历每一页
for (HSLFSlide slide : ppt.getSlides()) {
// 遍历每一个形状
for (HSLFShape shape : slide.getShapes()) {
// 如果是图片
if (shape instanceof HSLFPictureShape) {
HSLFPictureShape pic = (HSLFPictureShape) shape;
// 获取图片索引
int index = pic.getPictureIndex();
// 设置新的ppi
pic.setPictureData(pictures[index]);
}
}
}
// 保存ppt
FileOutputStream out = new FileOutputStream("D:\\test_new.ppt");
ppt.write(out);
out.close();
// 还原ppi
ppt.getSlideMasters()[0].getApplicationData().setPointsPerInch(defaultPpi);
}
}