从Java InputStream打开图像文件

4

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

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

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

我可以将它转换成ImageImageIconBufferedImage,但如何在默认的图像查看器中打开图像呢?
我的类名是'Test',我正在尝试访问的图像是C:\Users\Pranav\Documents\NetBeansProjects\Test\src\test\DSC_6283.jpg 任何帮助都将不胜感激。
2个回答

9

纯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());
}

Edit:

        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中盗用了这个版本。


非常感谢!:) 完美运行!您能否解释一下这些代码的作用-byte[] buffer = new byte[1024];int len; while ((len = imageStream.read(buffer)) != -1) { out.write(buffer, 0, len); } - Pranav
@Pranav 添加了注释 - Andreas
非常感谢!:D @Andreas - Pranav

0

2
临时文件夹可能比C:\更合适。 - jtahlborn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接