Is there a way to get Bing's photo of the day? - bing

Is there some way I could get the Bing background image programmatically?
Bing's API doesn't seem to provide such functionality, perhaps there's another way?

I think the best way is immitating the way they do it themselves through their AJAX calls.
They call this URL and extract the information through XML deserialization.
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
The mkt attribute can obviously be changed to a different region than ´en-US´, but can also be opted out of entirely if you don't care about a specific region.
Note that the _1366x768.jpg suffix that is added to the image names appears to be modifiable into different resolutions (like _1920x1080.jpg for full HD and possibly others).
Here's a dump of the data as of 9/28/2013, in XML format.
<?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>

JSON FORMAT of BING IMAGE
I found a way to fetch the JSON format of the Bing Image of the day
http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1
Note
n= The no of images u want( u can use Integers) ,
mkt= Your
location (example: en-US)
Here is the JSON output looks like
{
"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."
}
}
use the url from the images[]
and add it to 'http://bing.com'
here url is "url": "\/az\/hprichbg\/rb\/DayGecko_EN-US8730336235_1366x768.jpg"

One liner PowerShell (3.0 or higher)
irm is an alias for Invoke-RestMethod
irm "bing.com$((irm "bing.com/HPImageArchive.aspx?format=js&mkt=en-IN&n=1").images[0].url)" -OutFile bing.jpg

Microsoft has recently published a Bing Dynamic Theme for Windows 7, which contains an RSS Feed with links to Bing wallpapers.
There's also a Python script which tries to load the Bing website and guess the correct image URL, but from my experience, it usually results in a lower resolution image than those offered by the RSS feed.

I'm late to the party, but in case someone needs a PHP implementation: I've written a simple class which handles the procedure:
https://github.com/grubersjoe/bing-daily-photo

I like Bing images too but their app is too bloated for the purpose of downloading images. After analyzing connection with fiddler, I wrote this code. The 1920x1200 comes with Bing logo embedded but lower resolutions do not have it.
You can have windows show you random images from the image folder you set, so as you download them daily, it'll show you more random images.
If you do keep the "imageDir", you need to change the permissions on that folder or it will crash, I did not bother with catching errors.
Lastly, un-comment the lines if you want to set your wallpaper to today's image or you can create a task to run the program, say a minute after logon.
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();
}
}
}
}

I saw that many people are asking for the new RSS link too, just change the format parameter in the URL to "rss".
RSS: http://www.bing.com/HPImageArchive.aspx?format=rss&idx=0&n=1&mkt=en-US

In case anyone is looking for possible implementations, I wrote a small command-line program in C# to download, save, and set my background as the Bing Image of the Day. Feel free to modify it to your personal needs. 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);
}
}
}

Bash one liner (needs bash, curl and jq), useful for putting in a cronjob:
BACKGROUND_META=$(curl 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US'); curl -o $(echo $BACKGROUND_META | jq -r '.images[0].urlbase' | sed s/.*=//).jpg "https://bing.com$(echo $BACKGROUND_META| jq -r '.images[0].url')"

This JavaScript will answer the 'what to do with the api' by changing the background image of a div to the background of the current day's bing image.
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%";
}
}
}

Have a look at bing-desktop-wallpaper-changer on Github. The script has been written in python and I hope you find your answer there.
#!/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)
Have a look at the Github project for detailed code

Simple PowerShell, place into a folder, create a daily task in Windows Task Scheduler, script saves images at its run folder, then in your Desktop Background settings choose that folder as a background.
[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)"

Here's a simple Python script to fetch the Bing photo of the day using just requests and json:
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))
This will write a file such as TurtleTears_EN-US7942276596_1920x1080.jpg to the same directory where the script is executed. Of course, can tweak a whole bunch of things here, but gets the job done reasonably easily.

I was having trouble getting a proper RSS feed that I could use with John’s Background Switcher until I found this feedburner feed which seems to work quite well: http://feeds.feedburner.com/bingimages

I just finally decided to write a script in Python 3 to get the most images (16) from the xml archive.
So now i can archive the images in no effort. Just run the Python script.
I organize the images into Year / Month folders like this: 2018 > 12 December > 2018-12-06.jpg
This script goes in my Bing Wallpapers folder. (which is in my Pictures folder)
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)
Optional extra code to update the wallpaper: (put beneath 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
example output:
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
P.S. the above script is using &mkt=en-NZ for the New Zealand images.
You can check out the market code for other countries here.
You can also see all the images archived since 2009 for different countries here.
(only in 1366x768 though)
Major P.S. add the script to Task Scheduler to run when logging on. (or daily/weekly)
Create Basic Task
Program/script: python (or C:\Python34\python.exe if it's not in your env path)
arguments: "path/to/your/script.py"
start in: "path/to/your"
UPDATE! (March 2019)
The image for 2019-03-10 was given wrong startdate (20190309) in both the xml and rss format.
Using Json format instead. (since it gives accurate date)

https://peapix.com/bing/feed will listing the latest Bing image without Bing logo , maintain by peapix.com. Supported the following country/region: AU,CA,CN,DE,FR,JP,US,GB.
for example, https://peapix.com/bing/feed?country=jp for Japan and https://peapix.com/bing/feed?country=us for the United States.

OP doesn't specify the operating system, so here is one for usage in Linux. I modified from the script offered here.
Basically it fetches the url of the image of the day, downloads the image and save to a fixed file ~/.config/wallpaper.jpg, and uses feh to set the wallpaper. At the same time sends a notification.
#!/bin/sh
WP_FILE=$HOME/.config/wallpaper.jpg
bing="www.bing.com"
# $xmlURL is needed to get the xml data from which
# the relative URL for the Bing pic of the day is extracted
#
# The mkt parameter determines which Bing market you would like to
# obtain your images from.
# Valid values are: en-US, zh-CN, ja-JP, en-AU, en-UK, de-DE, en-NZ, en-CA or opted out.
#
# The idx parameter determines where to start from. 0 is the current day,
# 1 the previous day, etc.
xmlURL="http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US"
# The desired Bing picture resolution to download
# Valid options: "_1024x768" "_1280x720" "_1366x768" "_1920x1200"
desiredPicRes="_1920x1080"
# The file extension for the Bing pic
picExt=".jpg"
# Extract the relative URL of the Bing pic of the day from
# the XML data retrieved from xmlURL, form the fully qualified
# URL for the pic of the day, and store it in $picURL
# Form the URL for the desired pic resolution
desiredPicURL=$bing$(curl -s $xmlURL | grep -oP "(?<=<urlBase>)(.*?)(?=</urlBase>)")$desiredPicRes$picExt
# Form the URL for the default pic resolution
defaultPicURL=$bing$(curl -s $xmlURL | grep -oP "(?<=<url>)(.*?)(?=</url>)")
# $picName contains the filename of the Bing pic of the day
# Attempt to download the desired image resolution. If it doesn't
# exist then download the default image resolution
if wget --quiet --spider "$desiredPicURL"
then
# Download the Bing pic of the day at desired resolution
curl -s -o "$WP_FILE" "$desiredPicURL"
else
# Download the Bing pic of the day at default resolution
curl -s -o "$WP_FILE" "$defaultPicURL"
fi
if [[ -f "${WP_FILE}" ]]; then
feh --bg-scale "$WP_FILE" && \
notify-send -i emblem-photos "Wallpaper" "Wallpaper changed" \
-h int:suppress-sound:1 -h int:transient:1
fi

You might consider getting the file_content of that url and search the file for the image.
Not sure that's the best way, but it is a way.

Using the URL from #Siv, here's an example of JavaScript that updates <div class="bgimg" id="background">
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()
}
The css for this class is:
.bgimg {
height: 100%;
position: relative;
opacity: 0.95;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}

You can do that using python and wget on a linux machine:
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
It downloads the daily bing background in the local directory under the name daily_im.jpg. You can put everything on a script.py and launch it programmatically.

EDIT 09/27/2018: http://www.istartedsomething.com/bingimages responds 404 for weeks. It may do not exist anymore. :-(
You can use istartedsomething.com's Bing Image Archive. It is an unofficial Bing Image Archive. It uses an homemade endpoint which is helpful to retrieve images:
GET /bingimages/getimage.php?id=<image_id>
id is a string containing the date when the image was published and the country where it was published. id has to comply with the following format: YYYYMMDD-xx, where:
YYYY is the year, written with four digits.
MM is the month, written with two digits.
DD is the day, written with two digits.
xx is the country indicator. Bing Image Archive currently supports the following countries:
au: Australia.
br: Brazil.
ca: Canada.
cn: China.
de: Deutschland.
fr: France.
gb: Great Britain.
jp: Japan.
nz: New Zealand.
uk: United Kingdom.
us: United States of America.
It returns an useful JSON object if it has some information or false if it hasn't got anything.
Example 1: Retriving the Bing daily image which was published on May, 24th 2014 in New Zealand
The image ID is 20140524-nz because the demanded image was published on 05/24/2014 and it was published in New Zealand, whose country indicator is nz.
http://www.istartedsomething.com/bingimages/getimage.php?id=20140524-nz returns the following piece of 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":[]
}
You can use the imageurl field or the url (Bing URL path) field to get your image.
Example 2: Retriving the Bing daily image which was published on July, 12th 1998 in France
The image ID is 19980712-fr because the demanded image was published on 07/12/1998 and it was published in France, whose country indicator is fr.
http://www.istartedsomething.com/bingimages/getimage.php?id=19980712-fr returns false because there is no Bing Daily Image for France on 07/12/1998 (Bing did not even exist at this time).

Related

How to attach a google doc file as Microsoft Word doc

My first time here in Stack overflow. I'm just an amateur programmer trying to learn Google Apps script. I created a google form to get answers from users. I have transferred the answers to a google doc formatted according to our use in the office. I need to email the google doc back to the for user in microsoft word format. Sending as pdf is not a problem, but msword is a bit tricky.
I tried copying the recommendations i found here but I can't seem to get it to run. I hope someone can tell me what i'm doing wrong and what i need to doe. here's the relevant portion of the code:
`doc.saveAndClose(); // end of the transfer from google sheet to google doc. now to email...
var filename= ts+"-"+c_name1;
var compfile = DriveApp.getFilesByName(filename);
if (!compfile.hasNext())
{
console.error("Could not open file "+filename);
return;
}
var template = HtmlService.createTemplateFromFile('email_message');
var message = template.evaluate().getContent();
MailApp.sendEmail({
to:em,
subject: "Automated Complaint Assistant",
htmlBody: message,
attachments: compfile.next()}) // attachment is pdf file type. HOW TO SEND AS WORD?
`
I tried this function i found here:
`function EmailCompAsWordDoc(email, name, newCopyID) {
var subject = "Word version of Complaint";
var body = "\n\nHere is the Microsoft Word version of the draft Complaint";
var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' + newCopyID + '&exportFormat=docx';
var options = {
headers: {
Authorization: "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(url, options);
var doc = response.getBlob();
//Create the docx file in my TEMP folder in Google Drive and send
var file = DriveApp.createFile(doc).setName('Draft Complaint '+ name + '.docx');
DriveApp.getFolderById('<ID of my TEMP folder in Google Drive>').addFile(file);
var blob = DriveApp.getFileById(file.getId());
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
Body: body,
attachments:[blob]
});
//Remove the docx file from the TEMP folder
DriveApp.getFileById(file.getId()).setTrashed(true);
}
var compid = DriveApp.getFileById(filename.getId()) // error here. How to get the file ID for use by this custom function??
EmailCompAsWordDoc(em, c_name1, compid)
`
From your provided script, I understood that the value of filename is the string value of var filename = ts + "-" + c_name1;. I thought that this is the reason for your current issue of filename.getId is not a function.
In this case, how about the following modification?
From:
var compid = DriveApp.getFileById(filename.getId())
To:
var compid = DriveApp.getFilesByName(filename).next().getId();
In this case, it supposes that the values of filename and em and c_name1 of EmailCompAsWordDoc(em, c_name1, compid) are valid values. Please be careful about this.

How to print a file with Jscript

Goal
I want to print a file via a PDF printer which isn't the default printer. I was able to temporary change the normal printer to the PDF printer.
Problem
But I don't know how to print a .doc, .txt or .xls via Jscript. Also, I can't find a way to save the default printer name so I can switch back after I've printed the file.
Jscript code
var objShell = new ActiveXObject("Shell.Application");
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
try {
var PDFCreatorQueue = new ActiveXObject("PDFCreatorBeta.JobQueue");
PDFCreatorQueue.Initialize();
var sourceFile = WScript.Arguments(0)
var sourceFolder = objFSO.GetParentFolderName(sourceFile)
var sourceName = objFSO.GetBaseName(sourceFile)
var targetFile = sourceFolder + "\\" + sourceName + ".pdf"
//HERE GOES THE COMMAND TO SAVE THE CURRENT DEFAULT PRINTER NAME TO A TEMP VARIABLE
objNet.SetDefaultPrinter("PDFCreator");
//HERE GOES THE PRINT COMMAND WHICH I DON'T KNOW
// HERE GOES THE COMMAND TO CHANGE BACK TO THE OLD DEFAULT PRINTER
if(!PDFCreatorQueue.WaitForJob(3)) {
WScript.Echo("The print job did not reach the queue within " + 3 + " seconds");
}
else {
var job = PDFCreatorQueue.NextJob;
job.SetProfileByGUID("DefaultGuid");
job.ConvertTo(targetFile);
if(!job.IsFinished || !job.IsSuccessful) {
WScript.Echo("Could not convert the file: " + targetFile);
}
}
PDFCreatorQueue.ReleaseCom();
}
catch(e) {
WScript.Echo(e.message);
PDFCreatorQueue.ReleaseCom();
}
Use the ShellFolderItem.InvokeVerbEx() function. The JScript example code in the MSDN article shows how to use it. Make the first argument "print" and the second argument the name of the printer. So you can remove the code that tinkers with the default printer.
Printing web page from js is quite easy, you could use window.print() method over an iFrame ( this works only with file format wich can be displaied into a web page so it doesn't work with .doc extension)
<iframe id="textfile" src="text.txt"></iframe>
<button onclick="print()">Print</button>
<script type="text/javascript">
function print() {
var iframe = document.getElementById('textfile');
iframe.contentWindow.print();
}
</script>
These will show you a message box to select what printer you want to use a so on.
What are you asking for seems to be silent printing but it isn't standarized over all the broswer.
P.S. I think that isn't a good idea to use the printer to save this file to pdf, I think taht you could look at jsPDF (a js tools to create pdf) or you should consider to make the pdf generation serverside.

How to obtain the image path/ url from a file uploaded on an openshift data dir to be stored in a postgresql database?

I am a self-taught programming newbie here so please bear with me. I am trying to create a site which allows users to upload their images on. With the patience of another user, I was able to get some answers as to how to create and allow users to upload their images onto the data drive on openshift. However, now I need to be able to store the image path or url onto a postgresql database (which can be called on later) so that each user will be able to keep track of the images that they have uploaded. I am currently stymied by this.
Here are the fragments of code which I feel plays a big role in answering this question:
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column('todo_id', db.Integer, primary_key=True)
title = db.Column(db.String(60))
text = db.Column(db.String)
done = db.Column(db.Boolean)
pub_date = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
image_url = db.Column(db.String)
def __init__(self, title, text, image_url):
self.title = title
self.text = text
self.image_url = image_url
self.done = False
self.pub_date = datetime.utcnow()
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
#app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
return redirect(url_for('uploaded_file',
filename=filename))
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
#app.route('/new', methods=['GET', 'POST'])
#login_required
def new():
if request.method == 'POST':
if not request.form['title']:
flash('Title is required', 'error')
elif not request.form['text']:
flash('Text is required', 'error')
else:
todo = Todo(request.form['title'], request.form['text'])
todo.user = g.user
db.session.add(todo)
db.session.commit()
flash('Todo item was successfully created')
return redirect(url_for('index'))
return render_template('new.html')
The current code that I have is pieced together by various tutorials and examples.
Currently, I am trying to merge the "Todo" db, "upload" function and "new" function and am having very little success. Using the little knowledge I have, I have merely added the "image_url" portions in which will be a column that is intended to house the image path. I would greatly appreciate it if somebody could shed some light on this conundrum. Thanks a million.
Respectfully,
Max

ExcelSoftArtisans - Bug on Save method with open Stream - Cannot accessed closed file

I have the following issue:
I’m doing an export of an ASP.Net GridView directly to an excel file.
I’m setting an image as a header in this method:
private static void insertPageHeaderFooter(ExcelInterfaceSoftArtisans excel,DateTime generatedDateTime)
{
StringBuilder builderFooterLeft = new StringBuilder();
builderFooterLeft.Append("&08Comfone AG Tel: +41 31 341 10 10");
builderFooterLeft.Append("\r");
builderFooterLeft.Append("&08Nussbaumstrasse 25 Fax: +41 31 341 10 11");
builderFooterLeft.Append("\r");
builderFooterLeft.Append("&08CH-3000 Bern 22 www.comfone.com");
StringBuilder builderFooterRight = new StringBuilder();
String sDateTime = generatedDateTime.ToString(CultureInfoHandler.ShortDateShortTimeFormat);
builderFooterRight.Append("&08&F");
builderFooterRight.Append("\r");
builderFooterRight.Append(string.Format("&08 {0}", sDateTime));
builderFooterRight.Append("\r"); //new line
builderFooterRight.Append("&08Page &P of &N");
excel.SetHeader("&G", 0.6, HeaderFooterSection.Section.Left, false);
excel.SetFooter(builderFooterLeft.ToString(), HeaderFooterSection.Section.Left, false);
excel.SetFooter(builderFooterRight.ToString(), HeaderFooterSection.Section.Right, false);
}
protected void SetHeader(string sText, double dImageSizeFactor, HeaderFooterSection.Section section, Worksheet sheet)
{
string headerAbsolutePath = HttpContext.Current.Server.MapPath("~/Resources/Mandates/CHECF.png");
Stream imageStream = new FileStream(headerAbsolutePath, FileMode.Open, FileAccess.Read);
Size imageSize = Image.FromStream(imageStream).Size;
imageStream = new FileStream(headerAbsolutePath, FileMode.Open, FileAccess.Read);
HeaderFooterSection header = sheet.PageSetup.GetHeader(section);
header.SetContent(sText, imageStream);
header.SetContent(sText);
header.GetPicture().Height = (int)(imageSize.Height * dImageSizeFactor);
header.GetPicture().Width = (int)(imageSize.Width * dImageSizeFactor);
imageStream.Close();
}
As you can see on the last line, I close the Stream.
Now, I want to save my excel file this way:
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
excel.SaveWorkbook(sFileName, HttpContext.Current.Response, false);
/// <summary>
/// Saves the current Workbook under the given filename
/// </summary>
/// <param name="filename"></param>
/// <param name="response"></param>
/// <param name="openInBrowser"></param>
public void SaveWorkbook(string filename, HttpResponse response, bool openInBrowser)
{
if (book != null)
{
application.Save(book, response, filename, openInBrowser);
}
}
but when I close the stream in the SetHeader method, I get the following error:
Error Message: Cannot access a closed file.
Stack Trace: at System.IO.__Error.FileNotOpen()
at System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin)
and when I don’t close the stream in the SetHeader method, the file is correctly saved.
Are you aware of this bug? How is it possible that I need to have an open stream in order to save an excel file? What can I do to fix that?
I’m attaching you the whole classes I’m using, so you can identify the problem better.
Thanks for your quick answer and solution on this problem.
[Disclaimer: I am the product owner of OfficeWriter]
This issue has been confirmed as a bug and has been submitted to the OfficeWriter development team.
In the meantime, I would recommend Sam's suggested workaround of using the overload that takes the image's file path instead of the image stream.
Here is a generic code snippet for how to insert an image into the header of an Excel file using the file path overload of HeaderFooterSection.SetContent():
//Open the workbook and get a handle on the worksheet that will contain the
//image in the header
ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Open(Page.MapPath("\\template.xlsx"));
Worksheet ws = wb.Worksheets["Sheet1"];
//Set the header
HeaderFooterSection header = ws.PageSetup.GetHeader(HeaderFooterSection.Section.Left);
header.SetContent("&G", Page.MapPath("\\images\\image1.png"));
Please see our documentation for additional reference on the SetContent() overloads and using ExcelWriter to format headers and footers in workbooks.
This issue has been addressed in the recent 8.5.1 release of OfficeWriter. See the change log.

ASP.net MVC wkhtmltopdf system process font issue

I'm using the wkhtmltopdf application to convert my ASP.net MVC 2 rendered HTML into a PDF and display the PDF instead of the standard view for better print ability. Everything works great minus one thing. When I run wkhtmltopdf as a process in my MVC application on our webserver it does not display the installed barcode font in the PDF.
Here is the code for the process.
public void HtmlToPdf(string url, string appPath)
{
string message = null;
// to build command argument
StringBuilder argument = new StringBuilder();
// input html file
string switches = "";
switches += "--print-media-type ";
switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
switches += "--page-size Letter ";
switches += "--load-error-handling ignore ";
switches += "--username admin ";
switches += "--password pass ";
argument.Append(switches + " " + url + " " + "C:\\PDF\\temp.pdf");
// to call the exe to convert
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = "C:\\wkhtmltopdf\\wkhtmltopdf.exe";
p.StartInfo.WorkingDirectory = "C:\\wkhtmltopdf";
p.StartInfo.Arguments = argument.ToString();
p.Start();
p.WaitForExit();
message = p.StandardError.ReadToEnd();
if (string.IsNullOrEmpty(message))
{
message = p.StandardOutput.ReadToEnd();
}
else
{
System.Diagnostics.Debug.WriteLine(message);
}
}
Not really sure why it wont show the barcode because it shows in the when you render the html but not in when the wkhtmltopddf converts it to pdf. It also works correctly if you run wkhtmltopdf out side of my MVC application.
-Thanks for any help
Have you tried it in a while with an updated version of wkhtmltopdf?
Which version was this a problem with? I recently tried to generate using a random font I downloaded and it worked fine.
If you generate the PDF on a server the server needs the font too, I assume you know that but someone else reading might not realize it :)
Could I get the font in question to test on my system?
Was the conversion done in what environment? (Most likely not Linux due to asp.net, but asking just in case)