Отваряне на файл с изображение от java InputStream

Опитвам се да отворя файл с изображение, който е пакетиран в .jar файл, като използвам програмата за преглед на изображения по подразбиране на компютъра, на който изпълнявам програмата си.

Намерих множество отговори за това как да получа достъп до файлове, които са опаковани в буркан с помощта на InputStream, но как мога да отворя тези файлове с този InputStream?

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

Мога да конвертирам това в Image, ImageIcon или BufferedImage, но как да отворя допълнително изображението в програмата за преглед на изображения по подразбиране?

Името на класа ми е „Тест“, а изображението, до което се опитвам да отида, е C:\Users\Pranav\Documents\NetBeansProjects\Test\src\test\DSC_6283.jpg

Всяка помощ ще бъде оценена.


person Pranav    schedule 04.09.2014    source източник


Отговори (2)


Чиста 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

person Andreas    schedule 04.09.2014
comment
Благодаря много!:) Работи перфектно! Бихте ли обяснили как работят тези линии- byte[] buffer = new byte[1024]; int len; while ((len = imageStream.read(buffer)) != -1) { out.write(buffer, 0, len); } - person Pranav; 06.09.2014
comment
@Pranav добави коментари - person Andreas; 08.09.2014
comment
Благодаря много! :D @Андреас - person Pranav; 08.09.2014

  1. Запазете изображението локално (напр. c:\my_image.jpg), което не е във файла .jar
  2. Използвайте Runtime.getRuntime().exec("cmd your_command_here_to_open_image"); тук е връзка за cmd команда на windows: http://www.sevenforums.com/software/180378-where-windows-photo-viewer-default-location.html
person russu    schedule 04.09.2014
comment
вероятно временната папка би била по-подходяща от C:\ - person jtahlborn; 04.09.2014