Search code examples
javawindowsjna

Change wallpaper using java


I found this code on the internet for changing windows wallpaper using JNA library and it works just as I wanted but only with images outside of .jar program (here is a code)

public class Wallpaper {

public Wallpaper() {
    User32.INSTANCE.SystemParametersInfo(0x0014, 0, "C:\\Users\\Public\\Pictures\\Sample Pictures\\bg.jpg", 1);
}
public static interface User32 extends Library {

    User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class, W32APIOptions.DEFAULT_OPTIONS);

    boolean SystemParametersInfo(int one, int two, String s, int three);
}

}

is there a way to get the file from resources ? It doesn't work when I replace the file path with this

getClass().getResource("bg.jpg").getPath()

Solution

  • getResource retrieves resources from whereever your class files live, and this could be a network, generated on the fly, or, most likely, from within a jar file, and those aren't files. The windows API you are calling requires a file.

    Thus, the answer is :What you want, is impossible.

    But you can work around it.

    You can get the resource as a stream, open a file someplace, transfer the bytes over ('copying' the resource to a file) and then provide the file. Something like:

    Path p = Paths.get(System.getProperty("user.home"), "backgrounds", "bg.jpg");
    Files.createDirectories(p.getParent());
    try (InputStream in = Wallpaper.class.getResourceAsStream("bg.jpg");
      OutputStream out = Files.newOutputStream(p)) {
    
        in.transferTo(out);
    }
    User32.INSTANCE.SystemParametersInfo(0x0014, 0, p.getAbsolutePath().toString(), 1);
    

    NOTE: The correct usage of getResource is not via getClass() but: Wallpaper.class.getResource. getClass() breaks if subclassing.