Pillow crop images keeping the ratio having a max width and max height

时间:2018-04-18 18:14:27

标签: python pillow

I need to crop something using Pillow, by keeping the ratio, and max_height or max_width.

Some images can have a bigger width or a bigger height.

I tried:

        image_clone = image.copy()
        width_percent = (size['width'] / float(image_clone.size[0]))
        height = int((float(image_clone.size[1]) * float(width_percent)))
        image_clone.thumbnail((size['width'], height), Image.LANCZOS)

Doesn't work well for images that have a bigger width because the height will be small, and the image not very visible.

1 个答案:

答案 0 :(得分:1)

我不清楚。我之前看过这个代码,缩小图像,使其适合一个盒子。条件是选择较大的,因为它适用于肖像和风景以及方形尺寸:

    image_clone = image.copy()
    width_percent = (size['width'] / float(image_clone.size[0]))
    height_percent = (size['height'] / float(image_clone.size[1]))
    if width_percent > height_percent:
        height = int((float(image_clone.size[1]) * float(width_percent)))
        image_clone.thumbnail((size['width'], height), Image.LANCZOS)
    else:
        width = int((float(image_clone.size[0]) * float(height_percent)))
        image_clone.thumbnail((width, size['height']), Image.LANCZOS)

未测试。