将画布图像加载到Excel中

时间:2016-11-30 23:56:05

标签: java image canvas apache-poi javafx-8

我在Canvas上创建了一个情节。现在我想将图像添加到Excel文件中。

我知道如何从Canvas获取WritableImage,我知道我需要InputStream在Excel中使用addPicture()来编写图像。问题是如何将这两者联系起来。

我可以将此图像保存到文件,然后打开并将其加载到Excel,但也许有办法避免这种情况?

1 个答案:

答案 0 :(得分:0)

您可以使用PipedInputStream / PipedOutputStream来完成此操作:

Image image = ...
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);

PipedOutputStream pos;
try (PipedInputStream pis = new PipedInputStream()) {
    pos = new PipedOutputStream(pis);
    new Thread(() -> {
        try {
            ImageIO.write(bImage, "png", pos);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }).start();
    workbook.addPicture(pis, Workbook.PICTURE_TYPE_PNG);
} catch (IOException ex) {
    throw new IllegalStateException(ex);
}

或者您可以使用ByteArrayOutputStream将数据写入数组:

Image image = ...
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
    ImageIO.write(bImage, "png", bos);
} catch (IOException ex) {
    throw new IllegalStateException(ex);
}
workbook.addPicture(bos.toByteArray(), Workbook.PICTURE_TYPE_PNG);