使用 Java 在 Windows 7 上设置壁纸

发布于 2024-10-17 12:40:56 字数 8395 浏览 1 评论 0原文

我一直在尝试一个小程序,将桌面图像设置为当前的“每日天文图片”。我一直在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

献世佛 2024-10-24 12:40:56

你可以看一下 JAWC 是如何做到的。

FTS:

Jawc 代表只是另一个壁纸更换器,或者,如果您愿意,也可以是 JAva 壁纸更换器。
它是一个基于插件的壁纸更换器,可以从 > 更改您的桌面背景图片。许多不同的来源,例如您的 PC 文件夹、Flickr 或 VladStudio,仅取决于 >您启用了哪些插件。

Jawc 使用 Java 编写,并且经过测试可在 Windows、Linux 和 Mac Os X 系统上运行。

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.

两人的回忆 2024-10-24 12:40:56

除了罗德里戈的回答,请特别查看这些类:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文