Setting wallpaper on Windows 7 with Java
I have been experimenting with a small program to set the desktop image to the current "Astronomy Picture of the Day". I have been using the JNA suggestion to set the wallpaper from a similar question (). However, my code is not working. I am not sure what's wrong - I have little experience with JNA. Here is the code. Please ignore the completely misleading class names - I started with another project to get me going. The part that is not working is the final setting of the wallpaper - no errors get thrown it just doesn't do anything. The image saves fine.
Edit - I have decided to make a batch file that sets the registry keys and run that. The batch file works sometimes then refuses to work other times. So far it's a partial success! The program is now:
Edit 2- I imported the wallpaper code from Can I change my Windows desktop wallpaper programmatically in Java/Groovy? and once I remembered to close the output file (doh!) it worked fine.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import java.util.Iterator;
import javax.imageio.*;
import javax.imageio.stream.*;
public class RSSReader {
private class HTMLParse extends HTMLEditorKit
{
/**
* Call to obtain a HTMLEditorKit.Parser object.
*
* @return A new HTMLEditorKit.Parser object.
*/
public HTMLEditorKit.Parser getParser()
{
return super.getParser();
}
}
private class HREFCallback extends ParserCallback
{
private String base;
public HREFCallback(String base)
{
this.base = base;
}
@Override
public void handleStartTag(Tag t,
MutableAttributeSet a,
int pos)
{
if (t == HTML.Tag.A)
{
String href = (String)(a.getAttribute(HTML.Attribute.HREF));
if (href.endsWith("jpg") && href.startsWith("image"))
{
URL u_img;
try
{
u_img = new URL(base + href);
System.out.println(u_img.toString());
Image img = ImageIO.read(u_img);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
double aspectScreen = dim.getWidth() / dim.getHeight();
double aspectImage = img.getWidth(null) / img.getHeight(null);
System.out.println(Double.toString(aspectScreen)
+ " " + Double.toString(aspectImage));
if (aspectScreen / aspectImage > 1.1 || aspectScreen / aspectImage < 0.9)
{
int x = 0;
int y = 0;
int w = (int)img.getWidth(null);
int h = (int)img.getHeight(null);
if (aspectScreen > aspectImage)
{
// Image needs to be letterboxed
double newHeight = img.getWidth(null) / aspectScreen;
y = (int)((img.getHeight(null) - newHeight) / 2);
h = (int)newHeight;
}
else
{
double newWidth = img.getHeight(null) / aspectScreen;
x = (int)(img.getWidth(null) - newWidth / 2);
w = (int)newWidth;
}
img = Toolkit.getDefaultToolkit().createImage((new FilteredImageSource(img.getSource(),
new CropImageFilter(x,y,w,h))));
}
Image scaled = img.getScaledInstance(dim.width, dim.height, Image.SCALE_DEFAULT);
String l_appdata = System.getenv("APPDATA");
System.out.println(l_appdata);
if (!l_appdata.equals(""))
{
try {
BufferedImage bufImage =
new BufferedImage(scaled.getWidth(null), scaled.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics2D bufImageGraphics = bufImage.createGraphics();
bufImageGraphics.drawImage(scaled, 0, 0, null);
String dirname = l_appdata + "\\" + "APOD Wallpaper";
(new File(dirname)).mkdir();
String fname = dirname + "\\" + "apod_wallpaper1.jpg";
File outputfile = new File开发者_开发技巧(fname);
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1); // an integer between 0 and 1
// 1 specifies minimum compression and maximum quality
File file = new File(fname);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(bufImage, null, null);
writer.write(null, image, iwp);
writer.dispose();
String scriptName = dirname + "\\" + "setwallpaper.bat";
File s = new File(scriptName);
BufferedWriter wr = new BufferedWriter(new FileWriter(s));
wr.write(":: Configure Wallpaper");
wr.newLine();
wr.write("REG ADD \"HKCU\\Control Panel\\Desktop\" /V Wallpaper /T REG_SZ /F /D \"" + fname + "\"");
wr.newLine();
wr.write("REG ADD \"HKCU\\Control Panel\\Desktop\" /V WallpaperStyle /T REG_SZ /F /D 0");
wr.newLine();
wr.write("REG ADD \"HKCU\\Control Panel\\Desktop\" /V TileWallpaper /T REG_SZ /F /D 2");
wr.newLine();
wr.write(":: Make the changes effective immediately");
wr.newLine();
wr.write("%SystemRoot%\\System32\\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters");
wr.newLine();
wr.close();
String cmd = "cmd /C start /D\"" + dirname + "\" setwallpaper.bat ";
System.out.println(cmd);
Process p = Runtime.getRuntime().exec(cmd);
try
{
p.waitFor();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
private static RSSReader instance = null;
private RSSReader() {
}
public static RSSReader getInstance() {
if(instance == null) {
instance = new RSSReader();
}
return instance;
}
public void writeNews() {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
String base = "http://apod.nasa.gov/apod/";
URL u = new URL(base + "astropix.html"); // your feed url
BufferedReader in = new BufferedReader(new InputStreamReader(u
.openStream()));
HTMLEditorKit.Parser parse = new HTMLParse().getParser();
parse.parse(in,new HREFCallback(base),true);
}
catch (Exception ex)
{
//do nothing
}
}
public static void main(String[] args) {
RSSReader reader = RSSReader.getInstance();
reader.writeNews();
}
}
You can take a look and see how JAWC does it.
FTS:
Jawc stands for Just Another Wallpaper Changer or, if you prefer, JAva Wallpaper Changer. It is a Plugin-Based Wallpaper Changer and can change your desktop background picture from a > lot of different sources like your PC's folders, or Flickr, or VladStudio, just depending on > which plugins you enable.
Jawc is written using Java and it has been tested to work on Windows, Linux and Mac Os X systems.
Further to Rodrigo's answer, see these classes in particular: http://jawc-wallpaperc.svn.sourceforge.net/viewvc/jawc-wallpaperc/trunk/Jawc/src/it/jwallpaper/platform/impl/
精彩评论