python – How to transform a vertical image into a horizontal image?

python – How to transform a vertical image into a horizontal image?

The general pipeline would be to resize the input image to the desired height while keeping the aspect ratio. Youll 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.

Heres 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
----------------------------------------

python – How to transform a vertical image into a horizontal image?

Leave a Reply

Your email address will not be published.