Apache POI中的图像转换

时间:2013-01-22 04:21:33

标签: java spring apache-poi

我要求在Word文档中显示的浏览器上显示图像。我正在使用Apache POI提取图像但无法在broswser中打开它。我使用下面的代码来保存图像。

 picTable = doc.getPicturesTable();
 List pictures = picTable.getAllPictures();
 if(pictures){
      println("pictures::"+pictures.size())
      Picture pic = (Picture)pictures.get(0);
      file = new File("test.gif")
      FileOutputStream out = new FileOutputStream(file)
      out.write(pic.getContent())
      out.close()
 }

我在下面看到了界面方法:

在POI api中,`PicturesManager接口方法savePicture..which

  

存储图像(可能在磁盘上)。请注意不同的输出   格式支持不同的文件类型,因此可以进行图像转换   需要。例如,HTML浏览器通常支持PictureType.GIF,   PictureType.JPEG,PictureType.PNG,PictureType.TIFF,但很少   PictureType.EMF或PictureType.WMF。 FO(Apache FOP)至少支持   PNG和SVG类型。

任何人都已经实现了这个或任何想法在浏览器中显示此图像。 非常感谢你。

1 个答案:

答案 0 :(得分:0)

我有xls文档的示例,我的代码:

HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
if (patriarch != null) {
// Loop through the objects
for (HSSFShape shape : patriarch.getChildren()) {
    if (shape instanceof HSSFPicture) {
        HSSFPicture picture = (HSSFPicture) shape;
        if (picture.getShapeType() == HSSFSimpleShape.OBJECT_TYPE_PICTURE) {
            if (picture.getImageDimension() != null) {

                    HSSFPictureData pictureData = picture.getPictureData();
                    byte[] data = pictureData.getData();
                    String fileName = PATH + picture.getFileName() + "." + pictureData.suggestFileExtension();
                    File file = new File(fileName);
                    try (FileOutputStream fop = new FileOutputStream(file)) {

                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        fop.write(data);
                        fop.flush();
                        fop.close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }
}

}

在此示例中,PATH可变为服务器上的文件夹,例如'c:/ temp / img /'表示获胜或'/ www / images /'表示nix。

如果需要,可以查看pictureData.suggestFileExtension()以等于'png','jpg'等。

运行这样的代码之后,您可以直接在html页面中使用fileName,或者如果您使用代理,则可能需要执行一些其他操作来获取已保存图片的链接。