Search code examples
pythonimageresizepython-imaging-libraryphoto

How to transform a "vertical" image into a "horizontal" image?


I'm facing an issue in Python. I want a "vertical" image to be resized to 1920 x 1080 by filling the borders with a color (ex: white).

I want a picture like this one

Input

to be converted into a picture like this one

Desired output

I used Pillow in order to try something, but nothing very conclusive happened.


Solution

  • The general pipeline would be to resize the input image to the desired height while keeping the aspect ratio. You'll need to determine the size of the necessary border(s) from the target width and current width of the resized input image. Then, two approaches might be applicable:

    • Either use ImageOps.expand to directly add borders of the desired sizes and color.
    • Or, use Image.new to create to new image with the proper target size and desired color, and then use Image.paste to paste the resized input image into that image at the proper location.

    Here's some code for both approaches:

    from PIL import Image, ImageOps
    
    # Load input image
    im = Image.open('path/to/your/image.jpg')
    
    # Target size parameters
    width = 1920
    height = 1080
    
    # Resize input image while keeping aspect ratio
    ratio = height / im.height
    im = im.resize((int(im.width * ratio), height))
    
    # Border parameters
    fill_color = (255, 255, 255)
    border_l = int((width - im.width) / 2)
    
    # Approach #1: Use ImageOps.expand()
    border_r = width - im.width - border_l
    im_1 = ImageOps.expand(im, (border_l, 0, border_r, 0), fill_color)
    im_1.save('approach_1.png')
    
    # Approach #2: Use Image.new() and Image.paste()
    im_2 = Image.new('RGB', (width, height), fill_color)
    im_2.paste(im, (border_l, 0))
    im_2.save('approach_2.png')
    

    Both create an image like this:

    Output

    ----------------------------------------
    System information
    ----------------------------------------
    Platform:    Windows-10-10.0.16299-SP0
    Python:      3.8.5
    Pillow:      8.1.0
    ----------------------------------------