Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening an image file from java InputStream

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.

like image 967
Pranav Avatar asked Jan 09 '23 21:01

Pranav


1 Answers

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

like image 61
Andreas Avatar answered Jan 16 '23 01:01

Andreas