Calculate the height for a row of images with different aspect ratios
This file contains 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
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