使用Java在Windows 7上设置壁纸

时间:2011-02-15 17:32:17

标签: java windows-7

我一直在试验一个小程序,将桌面图像设置为当前的“当天的天文图片”。我一直在使用JNA建议从类似的问题设置壁纸()。但是,我的代码无效。我不确定是什么问题 - 我对JNA没什么经验。这是代码。请忽略完全误导性的类名 - 我从另一个项目开始,让我去。不起作用的部分是壁纸的最终设置 - 没有错误被抛出它只是没有做任何事情。图像保存得很好。

编辑 - 我已决定创建一个批处理文件来设置注册表项并运行它。批处理文件有时会工作,然后拒绝工作。到目前为止,它取得了部分成功!该计划现在:

编辑2-我从Can I change my Windows desktop wallpaper programmatically in Java/Groovy?导入了壁纸代码,一旦我记得关闭输出文件(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();
  }
}

2 个答案:

答案 0 :(得分:4)

您可以查看JAWC如何做到这一点。

FTS:

  

Jawc代表Just Another Wallpaper Changer,或者,如果您愿意,还可以代表JAva Wallpaper Changer。   它是一个基于插件的壁纸更换器,可以从&gt;更改您的桌面背景图片许多不同的来源,如你的PC的文件夹,或Flickr,或VladStudio,只是取决于&gt;您启用了哪些插件。

     

Jawc是使用Java编写的,它已经过测试,适用于Windows,Linux和Mac Os X系统。

答案 1 :(得分:1)