Skip to content

Instantly share code, notes, and snippets.

@ata4
Last active October 10, 2016 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ata4/381fa179a8cf9842c341cc390423f144 to your computer and use it in GitHub Desktop.
Save ata4/381fa179a8cf9842c341cc390423f144 to your computer and use it in GitHub Desktop.
Sets a random Spotlight image as wallpaper
import sys
import os
import struct
import ctypes
import imghdr
import random
SystemParametersInfoW = ctypes.windll.user32.SystemParametersInfoW
def set_wallpaper(path):
SPI_SETDESKWALLPAPER = 20
SPIF_UPDATEINIFILE = 1
SystemParametersInfoW(SPI_SETDESKWALLPAPER,
0,
path,
SPIF_UPDATEINIFILE)
def get_wallpaper():
SPI_GETDESKWALLPAPER = 115
wallpaper = ctypes.create_unicode_buffer(256)
SystemParametersInfoW(SPI_GETDESKWALLPAPER,
len(wallpaper),
ctypes.byref(wallpaper),
0)
return wallpaper.value
def get_screen_size():
SM_CXSCREEN = 0
SM_CYSCREEN = 1
width = ctypes.windll.user32.GetSystemMetrics(SM_CXSCREEN)
height = ctypes.windll.user32.GetSystemMetrics(SM_CYSCREEN)
return width, height
def probe_image(fname):
width = None
height = None
# borrowed from http://stackoverflow.com/a/20380514
if imghdr.what(fname) != 'jpeg':
return width, height
with open(fname, 'rb') as fhandle:
try:
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf:
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xff:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip `precision' byte.
height, width = struct.unpack('>HH', fhandle.read(4))
except Exception: #IGNORE:W0703
pass
return width, height
def main(argv):
path_appdata = os.getenv('APPDATA')
path_assets = os.path.join(path_appdata, '..\\Local\\Packages\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\LocalState\\Assets')
screen_width, screen_height = get_screen_size()
current = os.path.basename(get_wallpaper())
images = []
for file in os.listdir(path_assets):
# don't include the currently set wallpaper
if file == current:
continue
path = os.path.join(path_assets, file)
width, height = probe_image(path)
if width == screen_width and height == screen_height:
images.append(path)
if not images:
print('No suitable images found in assets folder')
return 1
set_wallpaper(random.choice(images))
if __name__ == '__main__':
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment