子兮子兮 子兮子兮

No can, but will.

目录
Java 版下载必应每日壁纸并自动设置 Windows 系统桌面(改编自 C# 版)
/    

Java 版下载必应每日壁纸并自动设置 Windows 系统桌面(改编自 C# 版)

哈哈,好久没有写博客了,已经荒废了,前几天在某 IT 网站看到一个用 C# 写的设置必应每日壁纸为 Windows 系统桌面,看了看源码是通过调用 User32.dll 进行设置的,刚刚最近做的项目更调用 dll 有关,感觉用 Java 也能做出来,果断用 Java 也写了一个,不过只实现了简单的下载保存图片并设置图片为桌面壁纸的功能,没有做到和 C# 版的那么强大,比较鸡肋,仅用于本人无聊时练练手,分享出来,有兴趣的可以到 GitHub 查看源码。

说明

必应每日壁纸 APIhttp://cn.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1

参数 format 可选值:xml / js (json)

必应每日故事 APIhttp://cn.bing.com/cnhp/coverstory/
无印图片链接前缀http://cn.bing.com/az/hprichbg/rb/ + 名称 + _ZH-CN + 图片编号_宽x高 + .jpg

一、C# 原版(可以选择尺寸和样式)

C++++.png

二、本人改编的 Java 版(默认 1080P 及填充)

1. 开始欢迎界面:

welcome.png

2. 主界面,自动下载并设置壁纸:

2017-09-07 今日白露

WhiteDew.png

2017-09-04

main.png

2017-09-03

setting.png

3. Alt + F12 打开/关闭信息控制台:

2017-09-04

console.png

2017-09-03

console.png

4. Ctrl + W 关闭程序

close.jpg

5. 特别说明:

虽然程序使用 Java 开发的,理论上也可以在 Mac 和 Linux 上运行,但是由于需要调用系统层的东西,在 Mac 及 Linux (在网上查到 Linux 可以通过执行终端命令来设置壁纸,未在程序中实现)运行并不能设置壁纸,只能够下载并保存必应每日壁纸图片:

on-macbook.jpg

only-windows.jpg

6. 2018-01-26 更新:添加快捷方式参数

通过在快捷方式后添加 -hide-h 打开程序提示设置壁纸完成后直接关闭程序,不显示主程序窗口:

iWallpaper-link

iWallpaper.gif

三、原 C# 版核心代码:

 1using System;
 2using System.Collections.Generic;
 3using System.Drawing;
 4using System.Drawing.Imaging;
 5using System.IO;
 6using System.Linq;
 7using System.Net;
 8using System.Runtime.InteropServices;
 9using System.Text;
10using System.Text.RegularExpressions;
11using System.Threading.Tasks;
12
13namespace BingWallpaperTest
14{
15    class Program
16    {
17        static void Main(string[] args)
18        {
19            setWallpaper();
20        }
21
22       /**
23         * 获取壁纸网络地址
24         */
25        public static string getURL()
26        {
27            string InfoUrl = "http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1";
28            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InfoUrl);
29            request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8";
30            string xmlDoc;
31            // 使用using自动注销HttpWebResponse
32             using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
33             {
34                 Stream stream = webResponse.GetResponseStream();
35                 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
36                 {
37                     xmlDoc = reader.ReadToEnd();
38                 }
39             }
40             // 使用正则表达式解析标签(字符串),当然你也可以使用XmlDocument类或XDocument类
41             Regex regex = new Regex("<Url>(?<MyUrl>.*?)</Url>", RegexOptions.IgnoreCase);
42             MatchCollection collection = regex.Matches(xmlDoc);
43             // 取得匹配项列表
44             string ImageUrl = "http://www.bing.com" + collection[0].Groups["MyUrl"].Value;
45             if (true)
46             {
47                 ImageUrl = ImageUrl.Replace("1366x768", "1920x1080");
48             }
49             return ImageUrl;
50         }
51 
52         public static void setWallpaper()
53         {
54             string ImageSavePath = @"D:\Program Files\BingWallpaper";
55             // 设置墙纸
56             Bitmap bmpWallpaper;
57             WebRequest webreq = WebRequest.Create(getURL());
58             // Console.WriteLine(getURL());
59             // Console.ReadLine();
60             WebResponse webres = webreq.GetResponse();
61             using (Stream stream = webres.GetResponseStream())
62             {
63                 bmpWallpaper = (Bitmap)Image.FromStream(stream);
64                 // stream.Close();
65                 if (!Directory.Exists(ImageSavePath))
66                 {
67                     Directory.CreateDirectory(ImageSavePath);
68                 }
69                 // 设置文件名为例:bing2017816.jpg
70                 bmpWallpaper.Save(ImageSavePath + "\\bing" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".jpg", ImageFormat.Jpeg); //图片保存路径为相对路径,保存在程序的目录下
71             }
72             // 保存图片代码到此为止,下面就是
73             string strSavePath = ImageSavePath + "\\bing" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".jpg";
74             setWallpaperApi(strSavePath);
75         }
76 
77         // 利用系统的用户接口设置壁纸
78         [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
79         public static extern int SystemParametersInfo(
80                 int uAction,
81                 int uParam,
82                 string lpvParam,
83                 int fuWinIni
84                 );
85         public static void setWallpaperApi(string strSavePath)
86         {
87             SystemParametersInfo(20, 1, strSavePath, 1);
88         }
89     }
90 }

四、Java 版核心代码(dom4j.jar / jna.jar + jna-platform.jar):

本来是想用 jcom.jar 去调用 dll 来设置壁纸的,奈何没弄出来,反而知道了还有一个叫 jna 的东西...

  1package cn.zixizixi.wallpaper;
  2
  3import java.io.BufferedReader;
  4import java.io.File;
  5import java.io.FileOutputStream;
  6import java.io.IOException;
  7import java.io.InputStream;
  8import java.io.InputStreamReader;
  9import java.io.OutputStream;
 10import java.net.SocketTimeoutException;
 11import java.net.URL;
 12import java.net.URLConnection;
 13
 14import org.dom4j.DocumentException;
 15import org.dom4j.DocumentHelper;
 16import org.dom4j.Element;
 17
 18import com.sun.jna.Library;
 19import com.sun.jna.Native;
 20import com.sun.jna.Platform;
 21import com.sun.jna.win32.StdCallLibrary;
 22
 23import cn.zixizixi.wallpaper.util.ConsoleDialog;
 24import cn.zixizixi.wallpaper.util.StrUtils;
 25
 26/**
 27 * 下载并设置必应每日桌面壁纸
 28 * @author Tanken·L
 29 * @version 20170901
 30 */
 31public class SetBingImage {
 32   
 33    private static boolean debug = true;
 34
 35    /**
 36     * 获取必应每日壁纸图片网络路径
 37     * @param custom
 38     * @return
 39     */
 40    public static String getUrl(String custom) {
 41        String infoUrl = "http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1";
 42        URL url = null;
 43        URLConnection urlConn = null;
 44        try {
 45            url = new URL(infoUrl);
 46            urlConn = url.openConnection();
 47            urlConn.setConnectTimeout(3000);
 48            BufferedReader bufRead = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
 49            StringBuilder strBud = new StringBuilder();
 50            String line = null;
 51            while ((line = bufRead.readLine()) != null) {
 52                strBud.append(line);
 53            }
 54	
 55            Element imgEle = DocumentHelper.parseText(strBud.toString()).getRootElement();
 56            infoUrl = "http://cn.bing.com" + imgEle.element("image").elementText("url");
 57            
 58            if (custom != null && custom.trim() != "") {
 59                infoUrl = infoUrl.replace("1366x768", custom);
 60            }
 61	
 62            return infoUrl;
 63        } catch (SocketTimeoutException e) {
 64            // "[TOE]请求接口连接超时:" + e.getMessage()
 65        } catch (IOException e) {
 66            // "[IOE]请求接口加载出错:" + e.getMessage()
 67        } catch (DocumentException e) {
 68            // "[DOE]请求接口解析出错:" + e.getMessage()
 69        } finally {
 70            url = null;
 71            urlConn = null;
 72        }
 73        return null;
 74    }
 75  
 76    /**
 77     * 保存网络图片到本地
 78     * @param size
 79     * @return
 80     */
 81    public static String downloadImage(String imageUrl) {
 82        String fileSepar = StrUtils.F_SEPAR;
 83        String savePath = StrUtils.U_HOME + fileSepar + "Pictures" + fileSepar + "BingWallpaper";
 84        try {
 85            URL url = new URL(imageUrl);
 86            URLConnection urlConn = url.openConnection();
 87            urlConn.setConnectTimeout(5000);
 88            File fileDir = new File(savePath);
 89            if(!fileDir.exists()){  
 90                fileDir.mkdirs();  
 91            }
 92            
 93            InputStream is = urlConn.getInputStream();
 94            byte[] bs = new byte[1024];
 95            int len;
 96            String fileName = imageUrl.substring(imageUrl.indexOf("_ZH-CN") + 6, imageUrl.length());
 97            String filePath = fileDir.getPath() + fileSepar + StrUtils.nowStr("yyyyMMdd_") + fileName;
 98            OutputStream os = new FileOutputStream(filePath);
 99            while ((len = is.read(bs)) != -1) {
100                os.write(bs, 0, len);
101            }
102            os.close();
103            is.close();
104		
105            return filePath;
106        } catch (IOException e) {
107            // "下载图片加载出错:" + e.getMessage();
108        } finally {
109            fileSepar = null;
110            savePath = null;
111            imageUrl = null;
112        }
113        return null;
114    }
115    
116    public static boolean setWinWallpaper(String filePath) {
117        boolean flag = false;
118        if (StrUtils.isEmpty(filePath)) {
119            // 图片路径为空,无法设置壁纸!
120        } else {
121            if (Platform.isWindows()) {
122                // 调用 User32 设置桌面背景
123                flag = User32.INSTANCE.SystemParametersInfoA(20, 1, filePath, 1);
124            } else {
125                // TODO Other OS 目前仅能设置 Windows 系统的壁纸,其他系统只能下载保存壁纸图片!
126            }
127        }
128        return flag;
129    }
130    
131    public interface CLibrary extends Library {
132        CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
133 
134        void printf(String format, Object... args);
135    }
136  
137    public interface User32 extends StdCallLibrary {
138        User32 INSTANCE = (User32) Native.loadLibrary("User32", User32.class);
139        /**
140         * 查询/设置系统级参数
141         * @param uAction 要设置的参数: 
142         *      6(设置视窗的大小) / 17(开关屏保程序) / 13, 24(改变桌面图标水平和垂直间距) / 15(设置屏保等待时间) / 
143         *      20(设置桌面背景墙纸) / 93(开关鼠标轨迹) / 97 (开关Ctrl+Alt+Del窗口)
144         * @param uParam 参数
145         * @param lpvParam 参数
146         * @param fuWinIni 
147         * @return 
148         */
149        public boolean SystemParametersInfoA(int uAction, int uParam, String lpvParam, int fuWinIni);   
150    }
151}

五、 程序下载:




我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=wh4u6zpyhe1d