【问题标题】:Load Canvas image into Excel将 Canvas 图像加载到 Excel 中
【发布时间】:2016-11-30 23:56:04
【问题描述】:

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

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

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

【问题讨论】:

  • 您也可以写入 ByteArrayOutputStream,而不是通过 ImageIO.write() 写入文件。接下来您可以通过 addPicture(new ByteArrayInputStream(bytes of the ByteArrayOutputStream)) 将图片添加到工作簿

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


【解决方案1】:

您可以使用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);

【讨论】:

    猜你喜欢
    • 2011-12-28
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2014-02-27
    相关资源
    最近更新 更多