如何将“垂直"转换为“垂直"?图像变成“水平"图像图像? [英] How to transform a "vertical" image into a "horizontal" image?
问题描述
我在Python中遇到了一个问题.我想要一个垂直"的通过使用彩色(例如:白色)填充边框,将图像大小调整为<code> 1920 x 1080 .
我想要一张这样的照片
要转换成这样的图片
我用枕头来尝试一些东西,但是没有什么决定性的事情发生.
一般的方法是在保持宽高比的同时将输入图像调整为所需的高度.您需要根据调整后的输入图像的目标宽度和当前宽度来确定必要边框的大小.然后,两种方法可能适用:
- 要么使用
----------------------------------------系统信息----------------------------------------平台:Windows-10-10.0.16299-SP0的Python:3.8.5枕头:8.1.0----------------------------------------
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
to be converted into a picture like this one
I used Pillow in order to try something, but nothing very conclusive happened.
解决方案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 useImage.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:
---------------------------------------- System information ---------------------------------------- Platform: Windows-10-10.0.16299-SP0 Python: 3.8.5 Pillow: 8.1.0 ----------------------------------------
这篇关于如何将“垂直"转换为“垂直"?图像变成“水平"图像图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Either use