# chroma-key a generated image on its corner colour, despeckle, crop to the content bbox, # and (optionally) downscale to a target width. For standalone art (logo, popup panels) — # unlike assets/_slice.py this does NOT split frames or force a sprite height. import sys from PIL import Image KEY_D2 = 60 * 60 def main(src, dst, target_w=None): im = Image.open(src).convert('RGBA') w, h = im.size px = im.load() bg = px[0, 0][:3] for x in range(w): for y in range(h): r, g, b, a = px[x, y] if (r - bg[0]) ** 2 + (g - bg[1]) ** 2 + (b - bg[2]) ** 2 < KEY_D2 or (min(r, b) > g + 40): px[x, y] = (0, 0, 0, 0) im = im.crop(im.getbbox()) if target_w and im.width > target_w: im = im.resize((target_w, max(1, round(im.height * target_w / im.width))), Image.LANCZOS) im.save(dst) print(dst, im.size) if __name__ == '__main__': main(sys.argv[1], sys.argv[2], int(sys.argv[3]) if len(sys.argv) > 3 else None)