Created
January 7, 2020 21:02
-
-
Save Pietrrrek/a25faa850c82ef9ac720d3613725cb82 to your computer and use it in GitHub Desktop.
Get a random xkcd comic and set it as wallpaper on Windows 10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes | |
import os | |
import shutil | |
import time | |
import urllib.request | |
from ctypes import wintypes | |
import requests # pip install requests | |
from PIL import Image # pip install pillow | |
# Get webpage as HTML | |
webpage = "https://c.xkcd.com/random/comic/" | |
fp = urllib.request.urlopen(webpage) | |
html = fp.read().decode("utf8") | |
fp.close() | |
# Find the line which contains the image url | |
# XKCD provides the link on a line with "Image URL: <image-url>" | |
matchline = "" | |
for line in html.splitlines(): | |
if "image url" in line.lower(): | |
matchline = line | |
# Extract the image-url from the html-line | |
imgurl = "" | |
for i in range(len(matchline)): | |
if matchline[i] == ":": | |
imgurl = matchline[i+1:] | |
imgurl.strip() | |
break | |
# Get image as stream | |
resp = requests.get(imgurl, stream=True) | |
resp.raw.decode_content = True | |
# Create new file, write to the file from the stream | |
filename = "wallpaper.png" | |
local_file = open(filename, "wb") | |
shutil.copyfileobj(resp.raw, local_file) | |
del resp | |
# Convert the image from PNG to BMP | |
Image.open(filename).save(filename := "wallpaper.bmp") | |
# Get the full path of the image | |
path = os.path.join(os.getcwd(), filename) | |
ctypes.windll.user32.SystemParametersInfoW(20, 0, path, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment