Skip to content

Instantly share code, notes, and snippets.

@kako-nawao
Last active October 16, 2016 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kako-nawao/a0d751cd006cf4068449818f5c0fc83a to your computer and use it in GitHub Desktop.
Save kako-nawao/a0d751cd006cf4068449818f5c0fc83a to your computer and use it in GitHub Desktop.
Calculate the height for a row of images with different aspect ratios
def calculate_tiled_row_height(row_width, space_width, num_images, sum_aspect)
"""
Calculate the height required for a row of tiled images based on the row width,
space between images, number of images and sum of aspect ratios of images.
"""
return (row_width - (num_images - 1) * space_width) / float(sum_aspect)
def get_image_rows(image_iter, row_width, row_min_aspect, space_width):
"""
Get a generator of image rows for the given image iterable, row width,
minimum aspect ratio and space between images.
"""
row_images = []
sum_aspect = 0
for image in image_iter:
# Append image and increase counter
row_images.append(image)
sum_aspect += float(image.width) / image.height
# If row is completed, yield it and reset images/aspect sum
if sum_aspect >= row_min_aspect:
yield {
'height': calculate_tiled_row_height(row_width, space_width, len(row_images), sum_aspect)
'images': row_images
}
row_images = []
sum_aspect = 0
# If any images remained, yield a final row
if row_images:
yield {
'height': calculate_tiled_row_height(row_width, space_width, len(row_images), sum_aspect)
'images': row_images
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment