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# 原版(可以选择尺寸和样式):

二、本人改编的 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# 版核心代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

> namespace BingWallpaperTest
> {
>     class Program
>     {
>         static void Main(string[] args)
>         {
>             setWallpaper();
>         }
> 
>        /**
> 	      * 获取壁纸网络地址
>   	  */
>         public static string getURL()
>         {
>             string InfoUrl = "http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1";
>             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InfoUrl);
>             request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8";
>             string xmlDoc;
>             // 使用using自动注销HttpWebResponse
>             using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
>             {
>                 Stream stream = webResponse.GetResponseStream();
>                 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
>                 {
>                     xmlDoc = reader.ReadToEnd();
>                 }
>             }
>             // 使用正则表达式解析标签(字符串),当然你也可以使用XmlDocument类或XDocument类
>             Regex regex = new Regex("<Url>(?<MyUrl>.*?)</Url>", RegexOptions.IgnoreCase);
>             MatchCollection collection = regex.Matches(xmlDoc);
>             // 取得匹配项列表
>             string ImageUrl = "http://www.bing.com" + collection[0].Groups["MyUrl"].Value;
>             if (true)
>             {
>                 ImageUrl = ImageUrl.Replace("1366x768", "1920x1080");
>             }
>             return ImageUrl;
>         }
> 
>         public static void setWallpaper()
>         {
>             string ImageSavePath = @"D:\Program Files\BingWallpaper";
>             //设置墙纸
>             Bitmap bmpWallpaper;
>             WebRequest webreq = WebRequest.Create(getURL());
>             //Console.WriteLine(getURL());
>             //Console.ReadLine();
>             WebResponse webres = webreq.GetResponse();
>             using (Stream stream = webres.GetResponseStream())
>             {
>                 bmpWallpaper = (Bitmap)Image.FromStream(stream);
>                 //stream.Close();
>                 if (!Directory.Exists(ImageSavePath))
>                 {
>                     Directory.CreateDirectory(ImageSavePath);
>                 }
>                 //设置文件名为例:bing2017816.jpg
>                 bmpWallpaper.Save(ImageSavePath + "\\bing" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".jpg", ImageFormat.Jpeg); //图片保存路径为相对路径,保存在程序的目录下
>             }
>             //保存图片代码到此为止,下面就是
>             string strSavePath = ImageSavePath + "\\bing" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".jpg";
>             setWallpaperApi(strSavePath);
>         }
> 
>         //利用系统的用户接口设置壁纸
>         [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
>         public static extern int SystemParametersInfo(
>                 int uAction,
>                 int uParam,
>                 string lpvParam,
>                 int fuWinIni
>                 );
>         public static void setWallpaperApi(string strSavePath)
>         {
>             SystemParametersInfo(20, 1, strSavePath, 1);
>         }
>     }
> }

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

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

package cn.zixizixi.wallpaper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.win32.StdCallLibrary;

import cn.zixizixi.wallpaper.util.ConsoleDialog;
import cn.zixizixi.wallpaper.util.StrUtils;

/**

  • 下载并设置必应每日桌面壁纸
  • @author Tanken·L
  • @version 20170901
    */
    public class SetBingImage {
private static boolean debug = true;
/**
 * 获取必应每日壁纸图片网络路径
 * @param custom
 * @return
 */
public static String getUrl(String custom) {
    String infoUrl = "http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1";
    URL url = null;
    URLConnection urlConn = null;
    try {
        url = new URL(infoUrl);
        urlConn = url.openConnection();
        urlConn.setConnectTimeout(3000);
        BufferedReader bufRead = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
        StringBuilder strBud = new StringBuilder();
        String line = null;
        while ((line = bufRead.readLine()) != null) {
            strBud.append(line);
        }
        Element imgEle = DocumentHelper.parseText(strBud.toString()).getRootElement();
        infoUrl = "http://cn.bing.com" + imgEle.element("image").elementText("url");
        
        if (custom != null && custom.trim() != "") {
            infoUrl = infoUrl.replace("1366x768", custom);
        }
        return infoUrl;
    } catch (SocketTimeoutException e) {
        // "[TOE]请求接口连接超时:" + e.getMessage()
    } catch (IOException e) {
        // "[IOE]请求接口加载出错:" + e.getMessage()
    } catch (DocumentException e) {
        // "[DOE]请求接口解析出错:" + e.getMessage()
    } finally {
        url = null;
        urlConn = null;
    }
    return null;
}
/**
 * 保存网络图片到本地
 * @param size
 * @return
 */
public static String downloadImage(String imageUrl) {
    String fileSepar = StrUtils.F_SEPAR;
    String savePath = StrUtils.U_HOME + fileSepar + "Pictures" + fileSepar + "BingWallpaper";
    try {
        URL url = new URL(imageUrl);
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(5000);
        File fileDir = new File(savePath);
        if(!fileDir.exists()){  
            fileDir.mkdirs();  
        }
        
        InputStream is = urlConn.getInputStream();
        byte[] bs = new byte[1024];
        int len;
        String fileName = imageUrl.substring(imageUrl.indexOf("_ZH-CN") + 6, imageUrl.length());
        String filePath = fileDir.getPath() + fileSepar + StrUtils.nowStr("yyyyMMdd_") + fileName;
        OutputStream os = new FileOutputStream(filePath);
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        is.close();
        return filePath;
    } catch (IOException e) {
        // "下载图片加载出错:" + e.getMessage();
    } finally {
        fileSepar = null;
        savePath = null;
        imageUrl = null;
    }
    return null;
}
public static boolean setWinWallpaper(String filePath) {
    boolean flag = false;
    if (StrUtils.isEmpty(filePath)) {
        // 图片路径为空,无法设置壁纸!
    } else {
        if (Platform.isWindows()) {
            // 调用 User32 设置桌面背景
            flag = User32.INSTANCE.SystemParametersInfoA(20, 1, filePath, 1);
        } else {
            // TODO Other OS 目前仅能设置 Windows 系统的壁纸,其他系统只能下载保存壁纸图片!
        }
    }
    return flag;
}
public interface CLibrary extends Library {
    CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
    void printf(String format, Object... args);
}
public interface User32 extends StdCallLibrary {
    User32 INSTANCE = (User32) Native.loadLibrary("User32", User32.class);
    /**
     * 查询/设置系统级参数
     * @param uAction 要设置的参数: 
     *      6(设置视窗的大小) / 17(开关屏保程序) / 13, 24(改变桌面图标水平和垂直间距) / 15(设置屏保等待时间) / 
     *      20(设置桌面背景墙纸) / 93(开关鼠标轨迹) / 97 (开关Ctrl+Alt+Del窗口)
     * @param uParam 参数
     * @param lpvParam 参数
     * @param fuWinIni 
     * @return 
     */
    public boolean SystemParametersInfoA(int uAction, int uParam, String lpvParam, int fuWinIni);   
}

}


五、 程序下载:

  1. 可执行 Jar 包: iWallpaper.jar / 从 GitHub 下载
  2. 源代码: GitHub

好久没写博客了,好累 😫 .........
Done.

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

作者:Tanken

来源:http://pipe.b3log.org/blogs/Tanken/articles/2017/09/03/1539738313784