Skip to content

Instantly share code, notes, and snippets.

@coleifer
Created August 22, 2013 15:04
Show Gist options
  • Save coleifer/2a35418b520c8e1ec4fd to your computer and use it in GitHub Desktop.
Save coleifer/2a35418b520c8e1ec4fd to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os
import re
import sys
from PIL import Image
HOME = os.environ['HOME']
try:
screen_info = os.popen('xrandr').readlines()
resolution_re = re.compile('\s+(\d+)x(\d+)\s+\d+\.\d+\*')
for line in screen_info:
match_obj = resolution_re.search(line)
if match_obj:
WIDTH, HEIGHT = map(int, match_obj.groups())
break
except:
WIDTH = 1440
HEIGHT = 900
RATIO = float(WIDTH) / HEIGHT
def local_file(filename):
return os.path.join(HOME, filename)
def make_wallpapers(original):
im = Image.open(original)
width, height = im.size
ratio = float(width) / height
if ratio > RATIO:
# resize to match height, then crop horizontally from center
new_width = int(HEIGHT * ratio)
im.thumbnail((new_width, HEIGHT), Image.ANTIALIAS)
offset = (new_width - WIDTH) / 2
cropped = im.crop((offset, 0, offset + WIDTH, HEIGHT))
elif ratio < RATIO:
# resize to match width, then crop vertically from center
new_height = int(WIDTH / ratio)
im.thumbnail((WIDTH, new_height), Image.ANTIALIAS)
offset = (new_height - HEIGHT) / 2
cropped = im.crop((0, offset, WIDTH, offset + HEIGHT))
else:
im.thumbnail((WIDTH, HEIGHT), Image.ANTIALIAS)
cropped = im
path, ext = os.path.splitext(original)
dest_jpg = local_file('.wallpaper.jpg')
dest_png = local_file('.wallpaper.png')
cropped.save(dest_jpg, 'JPEG', quality=100)
cropped.save(dest_png, 'PNG')
def panic(msg):
print >> sys.stderr, msg
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) != 2:
panic('Error, missing required image file')
filename = sys.argv[-1]
if not os.path.exists(filename):
panic('Error, file %s not found' % filename)
make_wallpapers(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment