java一键换壁纸_Java 版下载必应每日壁纸并自动设置 Windows 系统桌面(改编自 C# 版)...

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

说明

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

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

abedcbec1df53fcacd61d2730391513f.png

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

1. 开始欢迎界面:

a86a23c88a6a10179aa4690a5a58db50.png

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

2017-09-07 今日白露

9ad202bcb0b5f9adb1da274877204557.png

2017-09-04

afe01783c9ea5b8cfd1bed75e7b645a0.png

2017-09-03

e9fadf7b652cb693abebf73a214d4f94.png

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

2017-09-04

aa9df3134e833e4bb77503da4ae74d46.png

2017-09-03

0be304bcdae95e626d95eb4e667672e7.png

4. Ctrl + W 关闭程序

7ec2f98afc27c0bbbaa4874ca06ba664.png

5. 特别说明:

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

bab391668aeed2f3a33766ec56d22b53.png

e4a17e2900d23e0670a4e735bc60a160.png

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

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

a5240b530bdd90b27b626d54020f55a1.png

83680c4ef63b1b493274c1cd6699cabb.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("(?.*?)", 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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值