有没有办法以编程方式获取Bing背景图像?
Bing的API似乎没有提供这样的功能,也许还有另一种方式?
我认为最好的方法是模仿他们通过AJAX调用自己做的方式。
他们调用此URL并通过XML反序列化提取信息。
XML:http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US
JSON:http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US
RSS:http://www.bing.com/HPImageArchive.aspx?format=rss&idx=0&n=1&mkt=en-US
mkt
属性显然可以更改为与'en-US'不同的区域,但如果您不关心特定区域,也可以完全取消选择。
请注意,添加到图像名称的_1366x768.jpg
后缀似乎可以修改为不同的分辨率(如全高清和其他可能的_1920x1080.jpg
)。
以下是截至2013年9月28日的数据转储,采用XML格式。
<?xml version="1.0" encoding="utf-8"?>
<images>
<image>
<startdate>20130928</startdate>
<fullstartdate>201309280000</fullstartdate>
<enddate>20130929</enddate>
<url>/az/hprichbg/rb/LakeTurkana_EN-US15976511099_1366x768.jpg</url>
<urlBase>/az/hprichbg/rb/LakeTurkana_EN-US15976511099</urlBase>
<copyright>Lava rock pools at the southern end of Lake Turkana, in Kenya (© Nigel Pavitt/Corbis)</copyright>
<copyrightlink>http://www.bing.com/search?q=Lake+Turkana%2C+Kenya&form=hpcapt</copyrightlink>
<drk>1</drk>
<top>1</top>
<bot>1</bot>
<hotspots>
<hotspot>
<desc>These are the southern reaches of a lake...</desc>
<link>http://www.bing.com/maps/?v=2&cp=2.794725~37.335197&lvl=7&dir=0&sty=b&q=Lake%20Turkana%2C%20Kenya&form=hphot1</link>
<query>That stretches for 180 miles, up into another country</query>
<LocX>15</LocX>
<LocY>33</LocY>
</hotspot>
<hotspot>
<desc>This body of water was once called the Jade Sea.</desc>
<link>http://www.bing.com/search?q=green+algae&form=hphot2</link>
<query>What gives the water here its sometimes vibrant hue?</query>
<LocX>37</LocX>
<LocY>42</LocY>
</hotspot>
<hotspot>
<desc>One of the world's most powerful predators lives here.</desc>
<link>http://www.bing.com/videos/search?q=Underwater+Croc+Cams+National+Geographic&FORM=hphot3#view=detail&mid=D25E1909D3514A8732C5D25E1909D3514A8732C5</link>
<query>See some rare underwater footage of the beast</query>
<LocX>66</LocX>
<LocY>33</LocY>
</hotspot>
<hotspot>
<desc>Many fossils of ancient human ancestors have been uncovered in the surrounding area.</desc>
<link>http://www.bing.com/search?q=Turkana+Boy&form=hphot4</link>
<query>One skeleton was so complete, paleoanthropologists gave him a name</query>
<LocX>82</LocX>
<LocY>41</LocY>
</hotspot>
</hotspots>
<messages></messages>
</image>
<tooltips>
<loadMessage>
<message>Indlæser...</message>
</loadMessage>
<previousImage>
<text>Forrige</text>
</previousImage>
<nextImage>
<text>Næste</text>
</nextImage>
<play>
<text>Afspil</text>
</play>
<pause>
<text>Pause</text>
</pause>
</tooltips>
</images>
简单的PowerShell,放入文件夹,在Windows任务计划程序中创建日常任务,脚本将图像保存在其运行文件夹中,然后在桌面背景设置中选择该文件夹作为背景。
[xml]$doc = (New-Object System.Net.WebClient).DownloadString("https://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=ru-RU")
$url = $doc.images.image.url
$url = "https://www.bing.com/" + $url -replace "_1366x768","_1920x1200"
Write-Output $url
$fileName = Split-Path $url -leaf
$output = "$PSScriptRoot\$fileName"
$start_time = Get-Date
Invoke-WebRequest -Uri $url -OutFile $output
Write-Output "Saved to: $output Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
让我告诉你如何使用javascript和php获取当天的日常壁纸,
试试这个js代码:
<script>
fetch('https://techytricks97.000webhostapp.com/')
.then(response => response.text())
.then(text=>{document.body.style.background="url('"+text+"')";document.body.style.backgroundSize='cover';});
</script>
这个脚本将当天的日常图像设置为html文档的背景(您可以根据您的使用情况进一步修改它)。
这个链接 - https://techytricks97.000webhostapp.com每天返回当天的bing壁纸。
fetch()
从https://techytricks97.000webhostapp.com
获取今天bing图像的网址,text=>{document.body.style.background="url('"+text+"')";document.body.style.backgroundSize='cover';}
将其设置为背景。
注意:Microsoft不允许使用bing daily的图像作为您网站的背景,您可以将其用作手机/桌面墙纸,或其他提及版权的内容。
这是在http://techytricks97.000webhostapp.com上使用的php代码:
<?php
header('Access-Control-Allow-Origin: *');
ini_set('display_errors', 1);
$reg=file_get_contents('https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN');
$reg=json_decode($reg);
$meka=$reg->images[0]->url;
echo('http://www.bing.com'.$meka);
?>
您可以只使用http://techytricks97.000webhostapp.com
,也可以在服务器上设置自己的php文件。
另一个注意事项:我没有使用javascript,因为浏览器的同源策略限制它,但允许从我的php文件中取出,因为我已经把header('Access-Control-Allow-Origin: *');
in我的PHP代码。我可以使用其他代理,但是他们的流量很高(我的网站一天几乎没有任何点击)。
如果您使用的是任何其他语言,则只需阅读此文件(http://techytricks97.000webhostapp.com)
我无法获得一个可以与John’s Background Switcher一起使用的正确RSS源,直到我发现这个看起来效果很好的feedburner feed:http://feeds.feedburner.com/bingimages
看看bing-desktop-wallpaper-changer上的Github。该脚本是用python编写的,我希望你在那里找到答案。
#!/usr/bin/python
#-*- coding: utf-8 -*-
import os
import urllib
import urllib2
from bs4 import BeautifulSoup
# Get BingXML file which contains the URL of the Bing Photo of the day
# idx = Number days previous the present day. 0 means current day, 1 means yesterday, etc
# n = Number of images predious the day given by idx
# mkt denotes your location. e.g. en-US means United States. Put in your country code
BingXML_URL = "http://www.bing.com/HPImageArchive.aspx? format=xml&idx=0&n=1&mkt=en-US"
page = urllib2.urlopen(BingXML_URL)
BingXML = BeautifulSoup(page, "lxml")
# For extracting complete URL of the image
Images = BingXML.find_all('image')
ImageURL = "https://www.bing.com" + Images[0].url.text
ImageName = Images[0].startdate.text+".jpg"
urllib.urlretrieve(ImageURL, ImageName)
看一下Github项目的详细代码
这是一个简单的Python脚本,只需使用requests
和json
即可获取当天的Bing照片:
import requests
import json
BING_URI_BASE = "http://www.bing.com"
BING_WALLPAPER_PATH = "/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US"
# open the Bing HPImageArchive URI and ask for a JSON response
resp = requests.get(BING_URI_BASE + BING_WALLPAPER_PATH)
if resp.status_code == 200:
json_response = json.loads(resp.content)
wallpaper_path = json_response['images'][0]['url']
filename = wallpaper_path.split('/')[-1]
wallpaper_uri = BING_URI_BASE + wallpaper_path
# open the actual wallpaper uri, and write the response as an image on the filesystem
response = requests.get(wallpaper_uri)
if resp.status_code == 200:
with open(filename, 'wb') as f:
f.write(response.content)
else:
raise ValueError("[ERROR] non-200 response from Bing server for '{}'".format(wallpaper_uri))
else:
raise ValueError("[ERROR] non-200 response from Bing server for '{}'".format(BING_URI_BASE + BING_WALLPAPER_PATH))
这会将TurtleTears_EN-US7942276596_1920x1080.jpg
等文件写入执行脚本的同一目录。当然,可以在这里调整一大堆东西,但可以轻松地完成工作。
我最后决定在Python 3中编写一个脚本来从xml存档中获取最多的图像(16)。
所以现在我可以毫不费力地存档图像。只需运行Python脚本。 我将图像组织成年/月文件夹,如下所示:2018> 12月12日> 2018-12-06.jpg
这个脚本进入我的Bing Wallpapers文件夹。 (在我的图片文件夹中)
import urllib.request as urllib
import json
from datetime import date
from dateutil import parser
import sys,os
months = "January","Febuary","March","April","May","June","July","August","September","October","November","December"
def downloadBingImages(start):
try: data = urllib.urlopen("https://www.bing.com/hpimagearchive.aspx?format=js&idx=%i&n=8&mkt=en-NZ"%start).read()
except: sys.exit()
e = json.loads(data.decode())
images = e["images"]
for image in images:
d = parser.parse(image["startdate"]) # parse("20181206")
filename = str(d.date())+".jpg" # 2018-12-06.jpg
folder = "%i/%i %s/"%(d.year,d.month,months[d.month-1]) # 2018/12 December/
file = folder+filename # 2018/12 December/2018-12-06.jpg
if not os.path.exists(folder): os.makedirs(folder)
exists = os.path.isfile(file)
url = "https://www.bing.com"+image["urlbase"]+"_1920x1200.jpg"
print(("downloading","exists")[exists],filename,url)
if not exists:
try: urllib.urlretrieve(url,file)
except: sys.exit()
print()
# downloads the 16 latest bing images
downloadBingImages(-1)
downloadBingImages(7)
更新壁纸的可选额外代码:(放在downloadBingImages(7)下面)
import ctypes,win32con
def getWallpaper():
ubuf = ctypes.create_unicode_buffer(512)
ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_GETDESKWALLPAPER,len(ubuf),ubuf,0)
return ubuf.value
def setWallpaper(path):
changed = win32con.SPIF_UPDATEINIFILE | win32con.SPIF_SENDCHANGE
ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_SETDESKWALLPAPER,0,path,changed)
# update wallpaper after a week from current
wallpaper = getWallpaper()
if wallpaper.startswith(os.getcwd()): # has to be in script directory
try: wallpaperDate = parser.parse(os.path.splitext(os.path.basename(wallpaper))[0])
except: sys.exit() # not using an image with a parsable date
t = date.today()
if (t-wallpaperDate.date()).days>=7: # been a week or longer
setWallpaper(os.path.abspath("%i/%i %s/"%(t.year,t.month,months[t.month-1])+str(t)+".jpg")) # .../2018/12 December/2018-12-14.jpg
示例输出:
exists 2018-12-15.jpg https://www.bing.com/az/hprichbg/rb/YosemiteBridge_ROW11493343707_1920x1200.jpg
exists 2018-12-14.jpg https://www.bing.com/az/hprichbg/rb/CardinalBerries_ROW13321753978_1920x1200.jpg
exists 2018-12-13.jpg https://www.bing.com/az/hprichbg/rb/ReykjavikYuleLads_ROW12406174277_1920x1200.jpg
exists 2018-12-12.jpg https://www.bing.com/az/hprichbg/rb/PoinsettiaBuds_ROW14015106672_1920x1200.jpg
exists 2018-12-11.jpg https://www.bing.com/az/hprichbg/rb/KilimanjaroMawenzi_ROW12001033920_1920x1200.jpg
exists 2018-12-10.jpg https://www.bing.com/az/hprichbg/rb/ChristmasIslandCrab_ROW12174154872_1920x1200.jpg
exists 2018-12-09.jpg https://www.bing.com/az/hprichbg/rb/JohnDaySnow_ROW10922424229_1920x1200.jpg
exists 2018-12-08.jpg https://www.bing.com/az/hprichbg/rb/BanffEvergreens_ROW13248925556_1920x1200.jpg
exists 2018-12-07.jpg https://www.bing.com/az/hprichbg/rb/TaisetsuShirakawago_ROW12053480529_1920x1200.jpg
exists 2018-12-06.jpg https://www.bing.com/az/hprichbg/rb/Huuhkajat_ROW11700922065_1920x1200.jpg
exists 2018-12-05.jpg https://www.bing.com/az/hprichbg/rb/SurfersBronteBeach_ROW9358782018_1920x1200.jpg
exists 2018-12-04.jpg https://www.bing.com/az/hprichbg/rb/SphinxObservatory_ROW9691446114_1920x1200.jpg
exists 2018-12-03.jpg https://www.bing.com/az/hprichbg/rb/HussarPoint_ROW8654856850_1920x1200.jpg
exists 2018-12-02.jpg https://www.bing.com/az/hprichbg/rb/Nuuk_ROW12381573676_1920x1200.jpg
exists 2018-12-01.jpg https://www.bing.com/az/hprichbg/rb/RedAntarctica_ROW12620598839_1920x1200.jpg
exists 2018-11-30.jpg https://www.bing.com/az/hprichbg/rb/KilchurnSky_ROW9474162800_1920x1200.jpg
附:上面的脚本使用&mkt=en-NZ
作为新西兰图像。
您可以查看其他国家here的市场代码。
您还可以查看自2009年以来针对不同国家here存档的所有图像。 (仅限1366x768)
主要人物将脚本添加到任务计划程序以在登录时运行。 (或每日/每周)
创建基本任务 程序/脚本:python(如果它不在你的env路径中,则为C:\ Python34 \ python.exe) 参数:“path / to / your / script.py” 开始于:“path / to / your”
UPDATE! (2019年3月) 2019-03-10的图像在xml和rss格式中都给出了错误的startdate(20190309)。 改用Json格式。 (因为它给出了准确的日期)
https://bingdesktop.com/gallery/feed
将列出没有Bing徽标的最新Bing图像,由bingdesktop.com维护。支持以下国家/地区:AU,CA,CN,DE,FR,JP,US,GB。
例如,日本的https://bingdesktop.com/gallery/feed?country=jp和美国的https://bingdesktop.com/gallery/feed?country=us。
您可以考虑获取该URL的file_content并在文件中搜索该图像。不确定这是最好的方式,但这是一种方式。
使用来自@Siv的URL,这是一个更新<div class="bgimg" id="background">
的JavaScript示例
function GetImageURL(ans) {
var suffix = ans.images[0].url
document.getElementById("background").style.backgroundImage = 'url("' +
'http://bing.com/' + suffix + '"'
}
function GetJSON() {
var xmlhttp = new XMLHttpRequest()
var url = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var ans = JSON.parse(this.responseText);
GetImageURL(ans);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
window.onload = function () {
GetJSON()
}
这堂课的CSS是:
.bgimg {
height: 100%;
position: relative;
opacity: 0.95;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
你可以在Linux机器上使用python和wget来做到这一点:
import os # import the os package
os.system("wget -O index.html http://www.bing.com") # download the bing index
str1 = open('index.html', 'r').read() # extract the file path using split
str2=str1.split("g_img={url: \"")[1]
str3=str2.split(".jpg")[0]
os.system("wget -O daily_im.jpg http://www.bing.com" + str3 + ".jpg") # donwload the daily image
它以名称daily_im.jpg下载本地目录中的每日bing背景。您可以将所有内容放在script.py上并以编程方式启动它。
我找到了一种获取当天Bing Image的JSON格式的方法
n=
你想要的图像的数量(你可以使用整数),
mkt=
您的位置(例如:en-US)
{
"images": [
{
"startdate": "20141214",
"fullstartdate": "201412141830",
"enddate": "20141215",
"url": "\/az\/hprichbg\/rb\/BlackButte_EN-IN7038391888_1920x1080.jpg",
"urlbase": "\/az\/hprichbg\/rb\/BlackButte_EN-IN7038391888",
"copyright": "Black Butte, seen from the Mount Jefferson Wilderness, Oregon, USA (\u00a9 Marc Adamus\/Aurora Photos)",
"copyrightlink": "http:\/\/www.bing.com\/search?q=Black+Butte&qs=n&form=hpcapt&mkt=en-in&pq=black+butte&sc=8-11&sp=-1&sk=&cvid=228ac7f125f94bbaafd4a4abd4f9a32d",
"wp": true,
"hsh": "94156ae1e2e1be49f9b739d2b7bff65c",
"drk": 1,
"top": 1,
"bot": 1,
"hs": [
],
"msg": [
{
"title": "How does it feel\u2026",
"link": "http:\/\/www.bing.com\/videos\/search?q=Climbing+Black+Butte&FORM=pgbar1&mkt=en-in#view=detail&mid=58BDB2F2B9FCB85D597558BDB2F2B9FCB85D5975",
"text": "To climb 1961.7 m?"
},
{
"title": "On top of the world",
"link": "http:\/\/www.bing.com\/images\/search?q=Pictures+From+the+Top+of+Mount+Everest&FORM=pgbar2&mkt=en-in",
"text": "It's mountaineer's dream view"
}
]
}
],
"tooltips": {
"loading": "Loading...",
"previous": "Previous",
"next": "Next",
"walle": "This image is not available to download as wallpaper.",
"walls": "Download this image. Use of this image is restricted to wallpaper only."
}
}
使用url
的images[]
并将其添加到'http://bing.com'
这里的网址是"url": "\/az\/hprichbg\/rb\/DayGecko_EN-US8730336235_1366x768.jpg"
编辑09/27/2018:http://www.istartedsomething.com/bingimages响应404周。它可能不再存在。 :-(
你可以使用istartedsomething.com's Bing Image Archive。这是一个非官方的Bing Image Archive。它使用自制端点,有助于检索图像:
GET /bingimages/getimage.php?id=<image_id>
id
是一个字符串,包含图像发布的日期和发布图像的国家/地区。 id
必须遵守以下格式:YYYYMMDD-xx
,其中:
YYYY
是一年,用四位数字写成。MM
是月份,用两位数字写成。DD
是一天,用两位数字写成。xx
是国家指标。 Bing Image Archive目前支持以下国家:
au
:澳大利亚。
br
:巴西。
ca
:加拿大。
cn
:中国。
de
:德国。
fr
:法国。
gb
:英国。
jp
:日本。
nz
:新西兰。
uk
:英国。
us
:美利坚合众国。如果它有一些信息,它返回一个有用的JSON对象,如果没有任何信息,则返回false。
示例1:检索2014年5月24日在新西兰发布的Bing日常图像
图片ID为20140524-nz
,因为要求的图片发布于2014年05月24日,并在新西兰出版,其国家指标为nz
。
http://www.istartedsomething.com/bingimages/getimage.php?id=20140524-nz返回以下JSON:
{
"url":"\/az\/hprichbg\/rb\/LakeMagadiFlamingos_ROW9792683076_1366x768.jpg",
"region":"nz",
"date":"2014-05-24",
"copyright":"Flamingos take flight, Lake Magadi, Kenya (\u00a9 Bobby Haas\/Getty Images)(Bing New Zealand)",
"imageurl":"http:\/\/www.istartedsomething.com\/bingimages\/cache\/LakeMagadiFlamingos_ROW9792683076_1366x768.jpg",
"hotspots":[],
"video":[]
}
您可以使用imageurl
字段或url
(Bing URL路径)字段来获取图像。
示例2:检索1998年7月12日在法国发布的Bing日常图像
图片ID为19980712-fr
,因为要求的图片于1998年12月7日发布,并在法国出版,其国家指标为fr
。
http://www.istartedsomething.com/bingimages/getimage.php?id=19980712-fr返回false
因为1998年7月12日法国没有Bing Daily Image(Bing此时甚至不存在)。
微软最近发布了适用于Windows 7的Bing Dynamic Theme,其中包含an RSS Feed with links to Bing wallpapers。
还有一个Python script试图加载Bing网站并猜测正确的图像URL,但根据我的经验,它通常会产生比RSS提供的图像分辨率低的图像。
我迟到了,但万一有人需要PHP实现:我写了一个简单的类来处理这个过程:
单线程PowerShell(3.0或更高版本)
irm
是Invoke-RestMethod
的化名
irm "bing.com$((irm "bing.com/HPImageArchive.aspx?format=js&mkt=en-IN&n=1").images[0].url)" -OutFile bing.jpg
我也喜欢Bing图像,但他们的应用程序太臃肿,无法下载图像。在分析了与fiddler的连接后,我编写了这段代码。 1920x1200嵌入了Bing徽标,但较低的分辨率没有它。
您可以让窗口显示您设置的图像文件夹中的随机图像,因此当您每天下载它们时,它会向您显示更多随机图像。如果你确实保留了“imageDir”,你需要更改该文件夹的权限,否则它将崩溃,我没有理会捕获错误。最后,如果要将壁纸设置为今天的图像,则可以取消注释行,或者可以创建一个任务来运行程序,比如登录后一分钟。
using System;
using System.IO;
using System.Net;
//using System.Runtime.InteropServices;
namespace Bing
{
class Program
{
// [DllImport("user32.dll", CharSet = CharSet.Auto)]
// private static extern Int32 SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, String pvParam, UInt32 fWinIni);
private static String imgDir = @"C:\Windows\Web\Wallpaper\Bing\";
static void Main(string[] args)
{
String imageFileName;
if (!Directory.Exists(imgDir))
Directory.CreateDirectory(imgDir);
for (byte i = 6; i >= 0; i--)
{
imageFileName = imgDir + DateTime.Today.AddDays(-i).ToString("yyy-MM-dd") + ".jpg";
if (!File.Exists(imageFileName))
{
string response = null;
Connect(ref response, i);
ProcessXml(ref response);
using (WebClient client = new WebClient())
client.DownloadFile("http://www.bing.com" + response + "_1920x1200.jpg", imageFileName);
}
}
//SystemParametersInfo(20, 0, imageFileName, 0x01 | 0x02);
}
private static void Connect(ref string res, byte i)
{
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://www.bing.com/hpimagearchive.aspx?format=xml&idx=" + i + "&n=1&mbl=1&mkt=en-ww");
webrequest.KeepAlive = false;
webrequest.Method = "GET";
using (HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse())
using (StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream()))
res = loResponseStream.ReadToEnd();
}
private static void ProcessXml(ref string xmlString)
{
using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("urlBase");
xmlString = reader.ReadElementContentAsString();
}
}
}
}
我看到很多人也在要求新的RSS链接,只需将URL中的format参数更改为“rss”即可。
RSS:http://www.bing.com/HPImageArchive.aspx?format=rss&idx=0&n=1&mkt=en-US
这个JavaScript将通过将div的背景图像更改为当天bing图像的背景来回答“如何处理api”。
function PullBackground() {
var ajaxRequest = new XMLHttpRequest(), background = '';
ajaxRequest.open('POST', "http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US", true);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send('');
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
background = ajaxRequest.responseText;
var res = background.split("<url>");
var res1 = res[1].split("</url>");
background = res1[0];
document.getElementById('NameOfTheDivToChange').style.backgroundImage = "url('http://bing.com" + background + "')"
document.getElementById('NameOfTheDivToChange').style.backgroundSize = "100%";
}
}
}
如果有人正在寻找可能的实现,我在C#中编写了一个小的命令行程序来下载,保存并设置我的背景作为当天的Bing图像。您可以根据自己的个人需求进行修改。 https://github.com/josueespinosa/BingBackground
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace BingBackground
{
class BingBackground
{
private static void Main(string[] args)
{
string urlBase = GetBackgroundUrlBase();
Image background = DownloadBackground(urlBase + GetResolutionExtension(urlBase));
SaveBackground(background);
SetBackground(background, PicturePosition.Fill);
}
private static dynamic DownloadJson()
{
using (WebClient webClient = new WebClient())
{
Console.WriteLine("Downloading JSON...");
string jsonString = webClient.DownloadString("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US");
return JsonConvert.DeserializeObject<dynamic>(jsonString);
}
}
private static string GetBackgroundUrlBase()
{
dynamic jsonObject = DownloadJson();
return "https://www.bing.com" + jsonObject.images[0].urlbase;
}
private static string GetBackgroundTitle()
{
dynamic jsonObject = DownloadJson();
string copyrightText = jsonObject.images[0].copyright;
return copyrightText.Substring(0, copyrightText.IndexOf(" ("));
}
private static bool WebsiteExists(string url)
{
try
{
WebRequest request = WebRequest.Create(url);
request.Method = "HEAD";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
catch
{
return false;
}
}
private static string GetResolutionExtension(string url)
{
Rectangle resolution = Screen.PrimaryScreen.Bounds;
string widthByHeight = resolution.Width + "x" + resolution.Height;
string potentialExtension = "_" + widthByHeight + ".jpg";
if (WebsiteExists(url + potentialExtension))
{
Console.WriteLine("Background for " + widthByHeight + " found.");
return potentialExtension;
}
else
{
Console.WriteLine("No background for " + widthByHeight + " was found.");
Console.WriteLine("Using 1920x1080 instead.");
return "_1920x1080.jpg";
}
}
private static Image DownloadBackground(string url)
{
Console.WriteLine("Downloading background...");
WebRequest request = WebRequest.Create(url);
WebResponse reponse = request.GetResponse();
Stream stream = reponse.GetResponseStream();
return Image.FromStream(stream);
}
private static string GetBackgroundImagePath()
{
string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Bing Backgrounds", DateTime.Now.Year.ToString());
Directory.CreateDirectory(directory);
return Path.Combine(directory, DateTime.Now.ToString("M-d-yyyy") + ".bmp");
}
private static void SaveBackground(Image background)
{
Console.WriteLine("Saving background...");
background.Save(GetBackgroundImagePath(), System.Drawing.Imaging.ImageFormat.Bmp);
}
private enum PicturePosition
{
Tile,
Center,
Stretch,
Fit,
Fill
}
internal sealed class NativeMethods
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
}
private static void SetBackground(Image background, PicturePosition style)
{
Console.WriteLine("Setting background...");
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Path.Combine("Control Panel", "Desktop"), true))
{
switch (style)
{
case PicturePosition.Tile:
key.SetValue("PicturePosition", "0");
key.SetValue("TileWallpaper", "1");
break;
case PicturePosition.Center:
key.SetValue("PicturePosition", "0");
key.SetValue("TileWallpaper", "0");
break;
case PicturePosition.Stretch:
key.SetValue("PicturePosition", "2");
key.SetValue("TileWallpaper", "0");
break;
case PicturePosition.Fit:
key.SetValue("PicturePosition", "6");
key.SetValue("TileWallpaper", "0");
break;
case PicturePosition.Fill:
key.SetValue("PicturePosition", "10");
key.SetValue("TileWallpaper", "0");
break;
}
}
const int SetDesktopBackground = 20;
const int UpdateIniFile = 1;
const int SendWindowsIniChange = 2;
NativeMethods.SystemParametersInfo(SetDesktopBackground, 0, GetBackgroundImagePath(), UpdateIniFile | SendWindowsIniChange);
}
}
}