Adding borders to an image using python

前端 未结 7 919
名媛妹妹
名媛妹妹 2020-11-29 05:10

I have a large number of images of a fixed size (say 500*500). I want to write a python script which will resize them to a fixed size (say 800*800) but will keep the origina

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 05:49

    PIL's crop method can actually handle this for you by using numbers that are outside the bounding box of the original image, though it's not explicitly stated in the documentation. Negative numbers for left and top will add black pixels to those edges, while numbers greater than the original width and height for right and bottom will add black pixels to those edges.

    This code accounts for odd pixel sizes:

    from PIL import Image
    
    with Image.open('/path/to/image.gif') as im:
        old_size = im.size
        new_size = (800, 800)
    
        if new_size > old_size:
            # Set number of pixels to expand to the left, top, right,
            # and bottom, making sure to account for even or odd numbers
            if old_size[0] % 2 == 0:
                add_left = add_right = (new_size[0] - old_size[0]) // 2
            else:
                add_left = (new_size[0] - old_size[0]) // 2
                add_right = ((new_size[0] - old_size[0]) // 2) + 1
    
            if old_size[1] % 2 == 0:
                add_top = add_bottom = (new_size[1] - old_size[1]) // 2
            else:
                add_top = (new_size[1] - old_size[1]) // 2
                add_bottom = ((new_size[1] - old_size[1]) // 2) + 1
    
            left = 0 - add_left
            top = 0 - add_top
            right = old_size[0] + add_right
            bottom = old_size[1] + add_bottom
    
            # By default, the added pixels are black
            im = im.crop((left, top, right, bottom))
    

    Instead of the 4-tuple, you could instead use a 2-tuple to add the same number of pixels on the left/right and top/bottom, or a 1-tuple to add the same number of pixels to all sides.

提交回复
热议问题