Created
July 25, 2014 17:26
-
-
Save nicksnell/cdb069ed71a044d4ba5d to your computer and use it in GitHub Desktop.
Create a mosaic of tiles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from PIL import Image, ImageOps | |
| import requests | |
| class Tiler(object): | |
| def __init__(self, images, rows=4, tile_size=(135, 135)): | |
| self.images = images | |
| self.rows = rows | |
| self.tile_size = tile_size | |
| self.output = 'tiler/output.jpg' | |
| self.working_file_name = 'tiler/tiltiler-working-cache' | |
| self.working_file_name_thumb = 'tiler/tiler-working-cache-thumb-%s' | |
| def download_raw_image(self, image): | |
| """Pull the raw image into a local cache""" | |
| try: | |
| r = requests.get(image) | |
| with open(self.working_file_name, 'wb') as f: | |
| for chunk in r.iter_content(50): | |
| f.write(chunk) | |
| except Exception, e: | |
| return False | |
| return True | |
| def build(self): | |
| """Build the mosaic from the raw images""" | |
| downloaded_images = [] | |
| # Loop over the images and build a set suitable for tiling | |
| for index, image in enumerate(self.images): | |
| # Get the image as a file | |
| fetched_raw = self.download_raw_image(image) | |
| fname_thumb = self.working_file_name_thumb % index | |
| if not fetched_raw: | |
| continue | |
| # Read in and create a thumbnail | |
| try: | |
| im = Image.open(self.working_file_name) | |
| thumb = ImageOps.fit(im, self.tile_size, Image.ANTIALIAS) | |
| thumb.save(fname_thumb, 'JPEG') | |
| except IOError: | |
| continue | |
| downloaded_images.append(fname_thumb) | |
| # Get the dimensions of the canvas | |
| items_per_row = (len(downloaded_images) / self.rows) | |
| width = self.tile_size[0] * items_per_row | |
| height = self.tile_size[1] * self.rows | |
| canvas = Image.new('RGB', (width, height), 'white') | |
| # Build the tiles on the canvas | |
| for index, image in enumerate(downloaded_images): | |
| # Open the thumb we created earlier | |
| im = Image.open(image) | |
| # Get the point | |
| top, left = 0, 0 | |
| top = self.tile_size[1] * (index / items_per_row) | |
| if index % items_per_row: | |
| left = self.tile_size[0] * (index % items_per_row) | |
| # Paste the thumb on the canvas | |
| canvas.paste(im, (left, top)) | |
| # Save out the canvas | |
| canvas.save(self.output, 'JPEG') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment