【问题标题】:Passing a BufferedImage into a FileInputStream meant for image files将 BufferedImage 传递给用于图像文件的 FileInputStream
【发布时间】:2020-10-19 05:46:11
【问题描述】:

我有两段独立的代码需要一起工作,一段是我自己编写的,另一段来自另一个项目。我基本上有一部分项目正在创建缓冲图像。这是其中的一个sn-p:

BufferedImage screenshot = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);

在另一个软件中,它接受一个图像文件,然后作为 JSON/POST 数据传递给另一个服务。这是它接受一个文件:

try(InputStream file = new FileInputStream("temp.png")) {
                sendFile(out, "file", file, "temp.png");
            }

我没有太多使用 Java 处理图像的经验,我目前的解决方案是让第一个程序将 BufferedImage 写入这样的文件:

File tempFile = new File("/", "temp.png");
ImageIO.write(screenshot, "PNG", tempFile);

那么第二段代码就可以正确处理了。问题源于它需要删除临时文件以及由此产生的问题。有没有办法简化这个?提前致谢。

【问题讨论】:

  • 所以其他程序需要将图像作为文件接收?或者它可以接受类似 ByteStream 的东西吗?
  • 看起来 sendFile 方法不一定需要“文件”而是“输入流”。所以你可以尝试在这里创建一个:stackoverflow.com/a/5194876/11905620.
  • @EvanEdwards 如果您可以可靠地知道文件何时使用完毕,是的,您可以自己删除它们。但是,如果这两个服务都在持续运行,那么重构使用流可能会更好。 :-)
  • @EvanEdwards,听起来像是将它们保存在“内存文件”中,换句话说,通过 ByteArrayInput/OutputStream 的 ByteArray 可能是完美的。
  • 听起来不错,谢谢大家的帮助。明天早上我会阅读更多内容并尝试解决这个问题!

标签: java bufferedimage fileinputstream


【解决方案1】:

感谢@Mas 和评论者提供的链接,找到了解决方案。

第一组代码添加了一个名为“screenshotOutput”的ByteArrayOutputStream

ByteArrayOutputStream screenshotOutput = new ByteArrayOutputStream();
ImageIO.write(screenshot, "png", screenshotOutput);

第二组代码被修改为接受 ByteArrayInput 流。

try(InputStream file = new ByteArrayInputStream(screenshotOutput.toByteArray());) {
                sendFile(out, "file", file, "temp.png");
            }

这解决了我的问题。再次感谢昨天的评论。

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 2023-03-22
    • 1970-01-01
    • 2016-10-17
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    相关资源
    最近更新 更多