Create function tile().
authorPhilipp Spitzer <philipp@spitzer.priv.at>
Tue, 4 Jun 2019 21:04:11 +0000 (23:04 +0200)
committerPhilipp Spitzer <philipp@spitzer.priv.at>
Tue, 4 Jun 2019 21:08:04 +0000 (23:08 +0200)
gimp_passport.py
test_gimp_passport.py

index 9497fb0..540d00f 100644 (file)
@@ -1,4 +1,5 @@
 import argparse
+from itertools import count
 from numbers import Integral
 from PIL import Image
 
@@ -41,6 +42,27 @@ def make_passport(img_rgba: Image, fpr: float, width_mm: float, height_mm: float
     return pic
 
 
+def tile(img: Image, paper_width_mm: float, paper_height_mm: float, margin_mm: float) -> Image:
+    dpi = img.info['dpi'][0]
+    paper_width_pixel = int(round(paper_width_mm / MM_PER_INCH * dpi))
+    paper_height_pixel = int(round(paper_height_mm / MM_PER_INCH * dpi))
+    margin_pixel = mm_to_pixel(margin_mm, dpi)
+    paper = Image.new('RGB', (paper_width_pixel, paper_height_pixel), 'white')
+    paper.info['dpi'] = (dpi, dpi)
+    for iy in count():
+        top = margin_pixel + iy * img.height
+        bottom = top + img.height
+        if bottom > paper_height_pixel - margin_pixel:
+            break
+        for ix in count():
+            left = margin_pixel + ix * img.width
+            right = left + img.width
+            if right > paper_width_pixel - margin_pixel:
+                break
+            paper.paste(img, (left, top))
+    return paper
+
+
 def main(source_image: str, dest_image: str):
     img = Image.open(source_image)
     pic = make_passport(img, 0.75, 35., 45.)
index 37461c9..8e262b3 100644 (file)
@@ -1,6 +1,7 @@
 import os
 import unittest
-from gimp_passport import mm_to_pixel, main
+from PIL import Image, ImageDraw
+from gimp_passport import mm_to_pixel, main, tile
 
 
 class TestMakePassport(unittest.TestCase):
@@ -10,6 +11,15 @@ class TestMakePassport(unittest.TestCase):
         self.assertEqual(200, mm_to_pixel(25.4, 200))
         self.assertEqual(600, mm_to_pixel(2*25.4, 300))
 
+    def test_tile(self):
+        dpi = 90
+        img = Image.new('RGB', (mm_to_pixel(35, dpi), mm_to_pixel(45, dpi)), 'lightgray')
+        img.info['dpi'] = (dpi, dpi)
+        draw = ImageDraw.ImageDraw(img)
+        draw.rectangle((0, 0, img.size[0]-1, img.size[1]-1), outline='black')
+        paper = tile(img, 150, 100, 4)
+        self.assertIsInstance(paper, Image.Image)
+
     def test_main(self):
         source = 'test_image.png'
         dest = 'test_image_result.png'
@@ -17,4 +27,3 @@ class TestMakePassport(unittest.TestCase):
             os.remove(dest)
         main(source, dest)
         self.assertTrue(os.path.exists(dest))
-