Initial version creating a passport image from a .png with tranparency.
[toast/gimp_passport.git] / gimp_passport.py
1 from PIL import Image
2
3 def make_passport(image_filename: str, fpr: float, width_mm: float, height_mm: float) -> Image:
4     """
5     :param fpr: face to picture ratio, e.g. 2/3
6     """
7     img_rgba = Image.open(image_filename)
8
9     # get bounding box of head
10     bands = img_rgba.getbands()
11     if 'A' not in bands:
12         raise ValueError('Image has no transparency (needed for marking the head).')
13     alpha = img_rgba.getdata(bands.index('A'))
14     bbox_head = alpha.getbbox()  # bounding box of head
15
16
17     # get bounding box of passport image ("pic")
18     left, top, right, bottom = bbox_head
19     height = bottom - top
20     width = right - left
21     pic_height = int(round(height / fpr))
22     pic_width = int(round(pic_height * width_mm / height_mm))
23     pic_top = top - (pic_height - height) // 2
24     pic_bottom = pic_top + pic_height
25     pic_left = left - (pic_width - width) // 2
26     pic_right = pic_left + pic_width
27     bbox_pic = pic_left, pic_top, pic_right, pic_bottom
28
29     # cut image
30     img = img_rgba.convert('RGB')  # drop alpha channel
31     pic = img.crop(bbox_pic)
32     return pic
33
34
35 def main():
36     pic = make_passport('test_image.png', 0.75, 35., 45.)
37     pic.save('x.png')
38
39
40 main()