使用 Java 在 Windows 7 上设置壁纸
我一直在尝试一个小程序,将桌面图像设置为当前的“每日天文图片”。我一直在使用 JNA 建议来设置类似问题 () 中的壁纸。但是,我的代码不起作用。我不确定出了什么问题 - 我对 JNA 的经验很少。这是代码。请忽略完全误导性的类名 - 我从另一个项目开始让我继续前进。不起作用的部分是壁纸的最终设置 - 不会抛出任何错误,它只是不执行任何操作。图像保存得很好。
编辑 - 我决定制作一个设置注册表项的批处理文件并运行它。批处理文件有时可以工作,有时则无法工作。到目前为止,已经取得了部分成功!该程序现在是:
编辑2-我从 我可以在 Java/Groovy 中以编程方式更改 Windows 桌面壁纸吗? 一旦我记得关闭输出文件(doh!),它就工作得很好。
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();
}
}
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以看一下 JAWC 是如何做到的。
FTS:
You can take a look and see how JAWC does it.
FTS:
除了罗德里戈的回答,请特别查看这些类:
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/