Skip to main content

images/tint_image.py

1#!/usr/bin/env python3
2"""
3This is a script for creating colour-tinted versions of greyscale images.
5It works by creating an RGBA image which has the specified colour
6on every pixel, then controlling the intensity with the alpha value.
8I don't use it especially often, but I thought it was a neat trick and
9I wanted to save it for future use.
10"""
12import sys
14from PIL import Image
17if __name__ == "__main__":
18 try:
19 path = sys.argv[1]
20 hex_colour = sys.argv[2]
21 except IndexError:
22 sys.exit(f"Usage: {__file__} <PATH> <HEX_COLOUR>")
24 red = int(hex_colour[1:3], 16)
25 green = int(hex_colour[3:5], 16)
26 blue = int(hex_colour[5:7], 16)
28 im = Image.open(path)
29 im = im.convert("L")
30 pixels = list(im.getdata())
31 tinted_im = Image.new("RGBA", im.size)
33 if im.mode == "L":
34 tinted_im.putdata([(red, green, blue, 255 - p) for p in pixels])
35 else:
36 tinted_im.putdata([(red, green, blue, 255 - p[0]) for p in pixels])
38 name, _ = path.rsplit(".", 1)
39 out_path = f"{name}.{hex_colour.strip('#')}.png"
41 tinted_im.save(out_path)
42 print(out_path)