本文介绍了从 java InputStream 打开图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I am trying to open an image file that is packaged in a .jar file using the default image viewer of the computer on which i run my program.

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

I have found numerous answers about how to access files that are packaged in a jar using InputStream but how can i open those files using that InputStream?

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

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

I can convert this into an Image, ImageIcon or a BufferedImage but how to i further open the image in the default image viewer?

我的班级名称是Test",我尝试访问的图像是 C:\Users\Pranav\Documents\NetBeansProjects\Test\src\test\DSC_6283.jpg

My class name is 'Test' and the image i am trying to access is 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

注意,这是样板文件.我从 轻松获取此版本将 Java InputStream 的内容写入 OutputStream

Note, this is boilerplate. I stole this version from Easy way to write contents of a Java InputStream to an OutputStream

这篇关于从 java InputStream 打开图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:47