gpt4 book ai didi

java - 从 java InputStream 打开图像文件

转载 作者:行者123 更新时间:2023-12-01 14:09:38 25 4
gpt4 key购买 nike

我正在尝试使用运行程序的计算机的默认图像查看器打开打包在 .jar 文件中的图像文件。

我找到了很多关于如何使用 InputStream 访问打包在 jar 中的文件的答案,但是如何使用 InputStream 打开这些文件?

InputStream imageStream = Test.class.getClass().getResourceAsStream("/test/DSC_6283.jpg");

我可以将其转换为 Image , ImageIconBufferedImage但是如何在默认图像查看器中进一步打开图像?

我的类(class)名称是“Test”,我尝试访问的图像是 C:\Users\Pranav\Documents\NetBeansProjects\Test\src\test\DSC_6283.jpg
任何帮助,将不胜感激。

最佳答案

纯Java:

public static void main(String... args) throws IOException {
InputStream imageStream = Test.class.getClass().getResourceAsStream("/test/DSC_6283.jpg");
Path path = Files.createTempFile("DSC_6283", ".jpg");
try (FileOutputStream out = new FileOutputStream(path.toFile())) {
byte[] buffer = new byte[1024];
int len;
while ((len = imageStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
// TODO: handle exception
}
Desktop.getDesktop().open(path.toFile());
}

编辑:
        byte[] buffer = new byte[1024]; //allocate an array of bytes to use as a buffer. 1024 bytes in this case
int len; //a variable to record the number of bytes actually read from the stream each loop
while ((len = imageStream.read(buffer)) != -1) { //InputStream.read(byte[]) reads bytes from the stream and places them into the buffer. It returns the number of bytes placed into the buffer, or -1 if there is nothing more to read. We store that result in len, and evaluate if we should stop looping (ie if the return is -1)
out.write(buffer, 0, len); //write to the output file, from the buffer, starting at position 0, through the number of bytes read

请注意,这是样板文件。我从 Easy way to write contents of a Java InputStream to an OutputStream 那里偷了这个版本

关于java - 从 java InputStream 打开图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25669874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com