Initial version creating a passport image from a .png with tranparency.
authorPhilipp Spitzer <philipp@spitzer.priv.at>
Mon, 3 Jun 2019 20:20:51 +0000 (22:20 +0200)
committerPhilipp Spitzer <philipp@spitzer.priv.at>
Mon, 3 Jun 2019 20:20:51 +0000 (22:20 +0200)
gimp_passport.py [new file with mode: 0644]

diff --git a/gimp_passport.py b/gimp_passport.py
new file mode 100644 (file)
index 0000000..17d8f5f
--- /dev/null
@@ -0,0 +1,40 @@
+from PIL import Image
+
+def make_passport(image_filename: str, fpr: float, width_mm: float, height_mm: float) -> Image:
+    """
+    :param fpr: face to picture ratio, e.g. 2/3
+    """
+    img_rgba = Image.open(image_filename)
+
+    # get bounding box of head
+    bands = img_rgba.getbands()
+    if 'A' not in bands:
+        raise ValueError('Image has no transparency (needed for marking the head).')
+    alpha = img_rgba.getdata(bands.index('A'))
+    bbox_head = alpha.getbbox()  # bounding box of head
+
+
+    # get bounding box of passport image ("pic")
+    left, top, right, bottom = bbox_head
+    height = bottom - top
+    width = right - left
+    pic_height = int(round(height / fpr))
+    pic_width = int(round(pic_height * width_mm / height_mm))
+    pic_top = top - (pic_height - height) // 2
+    pic_bottom = pic_top + pic_height
+    pic_left = left - (pic_width - width) // 2
+    pic_right = pic_left + pic_width
+    bbox_pic = pic_left, pic_top, pic_right, pic_bottom
+
+    # cut image
+    img = img_rgba.convert('RGB')  # drop alpha channel
+    pic = img.crop(bbox_pic)
+    return pic
+
+
+def main():
+    pic = make_passport('test_image.png', 0.75, 35., 45.)
+    pic.save('x.png')
+
+
+main()