Opening an image file from java InputStream

别来无恙 提交于 2019-12-11 02:10:03

问题


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.

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

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

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

Any help would be appreciated.


回答1:


Pure 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

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




回答2:


  1. Save the image locally (ex. c:\my_image.jpg), which is not in the .jar file
  2. Use Runtime.getRuntime().exec("cmd your_command_here_to_open_image"); here is a link for cmd command on windows: http://www.sevenforums.com/software/180378-where-windows-photo-viewer-default-location.html


来源:https://stackoverflow.com/questions/25669874/opening-an-image-file-from-java-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!