将 BufferedImage 传递到用于图像文件的 FileInputStream

Passing a BufferedImage into a FileInputStream meant for image files

我有两段独立的代码需要协同工作,一段是我自己写的,一段来自另一个项目。我基本上有一个项目的一部分是创建缓冲图像。这是它的一个片段:

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);

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

感谢@Mas 和评论者的 link 找到了解决方案。

第一组代码添加了一个名为“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");
            }

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