代码如下:
from PIL import Image
# 读取图像
img = Image.open("mypic.jpg")
# 获取图像的宽度和高度
width, height = img.size
# 计算需要切割的区域的左上角和右下角坐标
if width / height >= 256 / 192: # 宽高比大于等于256/192
new_width = height / 192 * 256
left = (width - new_width) / 2
top = 0
right = left + new_width
bottom = height
else: # 宽高比小于256/192
new_height = width / 256 * 192
left = 0
top = (height - new_height) / 2
right = width
bottom = top + new_height
# 切割图像
img_cropped = img.crop((left, top, right, bottom))
# 调整图像大小
img_resized = img_cropped.resize((256, 192))
# 保存图像
img_resized.save("mypic_cropped.jpg")
我们首先使用Image.open()函数读取图像。然后,我们获取图像的宽度和高度,并根据比例计算需要切割的区域的左上角和右下角坐标。由于我们要去掉左右两边,因此top和bottom坐标保持不变,left和right坐标分别为图像宽度或高度根据比例调整后的值减去256或192再除以2,以确保切割区域居中。最后,我们使用crop()函数切割图像,再使用resize()函数将图像调整为192x256大小,并使用save()函数保存切割和调整大小后的图像