Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open an image in the default image viewer using Java on Windows?

I have a button to view an image attached to a log entry and when the user clicks that button I want it to open the image in the user's default image viewer on a Windows machine?

How do I know which viewer in the default image viewer?

Right now I'm doing something like this but it doesn't work:

String filename = "\""+(String)attachmentsComboBox.getSelectedItem()+"\"";
Runtime.getRuntime().exec("rundll32.exe C:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen "+filename);

And by doesn't work I mean it doesn't do anything. I tried to run the command just in the command line and nothing happened. No error, nothing.

like image 559
Brian T Hannan Avatar asked Apr 28 '11 20:04

Brian T Hannan


People also ask

What is the default Windows Image Viewer?

Windows 10 uses the new Photos app as your default image viewer, but many people still prefer the old Windows Photo Viewer.


1 Answers

Try with the CMD /C START

public class Test2 {
  public static void main(String[] args) throws Exception {
    String fileName = "c:\\temp\\test.bmp";
    String [] commands = {
        "cmd.exe" , "/c", "start" , "\"DummyTitle\"", "\"" + fileName + "\""
    };
    Process p = Runtime.getRuntime().exec(commands);
    p.waitFor();
    System.out.println("Done.");
 }
}

This will start the default photo viewer associated with the file extension.

A better way is to use java.awt.Desktop.

import java.awt.Desktop;
import java.io.File;

public class Test2 {
  public static void main(String[] args) throws Exception {
    File f = new File("c:\\temp\\test.bmp");
    Desktop dt = Desktop.getDesktop();
    dt.open(f);
    System.out.println("Done.");
 }
}

See Launch the application associated with a file extension

like image 191
RealHowTo Avatar answered Oct 22 '22 04:10

RealHowTo