分析接口

接口地址 https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US 这里面idx=0表示今天 n=1表示1张壁纸,最多可取8张. 获取回来的是json

取回来的url,去要加上https://cn.bing.com/就是图片地址,把当天年月日设置成文件名,就是当天图片.

go实现

首先建立文件夹,随机获取文件夹图片,调用api接口设置桌面即可.

package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"syscall"
	"time"
	"unsafe"
)

func main() {
//从bing网站下载当天壁纸,并设置为背景桌面
	downimg()
	img:=randimg()
	SetWindowsWallpaper(img)
}
func randimg()string{
	tempDir := os.TempDir()+"\\yobys_temp"
	var s []string
	var img string
	s,_=GetAllFile(tempDir,s)
	if len(s)==1{
		img=tempDir+"\\"+s[0]
	}else{
		rand.Seed(time.Now().Unix())
		v:=s[rand.Intn(len(s))]
		img=tempDir+"\\"+v
	}

	return img
}
func downimg(){
	tempDir := os.TempDir()+"\\yobys_temp"
	date := time.Now().Format("20060102")
	os.Mkdir(tempDir, 0666)
	if isExist(tempDir+"\\"+date+".jpg")==false{
		resp, _ := http.Get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US")
		body, _ := ioutil.ReadAll(resp.Body)
		var tempMap map[string][]interface{}
		json.Unmarshal(body, &tempMap)
		var vv map[string]interface{}
		vv=tempMap["images"][0].(map[string]interface{})
		url,_:= vv["url"].(string);
		url="https://cn.bing.com/"+url
		fmt.Println(date,url)
		resp1,_:=http.Get(url)
		body1, _ := ioutil.ReadAll(resp1.Body)
		out, _ := os.Create(tempDir+"\\"+date+".jpg")
		io.Copy(out, bytes.NewReader(body1))
	}

}
func isExist(path string)(bool){
	_, err := os.Stat(path)
	if err != nil{
		if os.IsExist(err){
			return true
		}
		if os.IsNotExist(err){
			return false
		}
		return false
	}
	return true
}
//设置桌面背景
func SetWindowsWallpaper(imagePath string) error {
	dll := syscall.NewLazyDLL("user32.dll")
	proc := dll.NewProc("SystemParametersInfoW")
	_t, _ := syscall.UTF16PtrFromString(imagePath)
	ret, _, _ := proc.Call(20, 1, uintptr(unsafe.Pointer(_t)), 0x1|0x2)
	if ret != 1 {
		return errors.New("系统调用失败")
	}
	return nil
}
//获取目录下文件
func GetAllFile(pathname string, s []string) ([]string, error) {
	rd, err := ioutil.ReadDir(pathname)
	if err != nil {
		fmt.Println("read dir fail:", err)
		return s, err
	}

	for _, fi := range rd {
		if !fi.IsDir() {
			fullName := fi.Name()
			s = append(s, fullName)
		}
	}
	return s, nil
}

上面就是切换壁纸完整代码.里面知识点很多.值得看一看.