How to cut pictures to get the size you want

code show as below:

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")

We first read the image using the Image.open() function. We then get the width and height of the image and calculate the upper left and lower right coordinates of the area that needs to be cut based on the ratio. Since we want to remove the left and right sides, the top and bottom coordinates remain unchanged. The left and right coordinates are the image width or height adjusted according to the proportion minus 256 or 192 and divided by 2 to ensure that the cutting area is centered. Finally, we use the crop() function to cut the image, then use the resize() function to resize the image to 192x256, and use the save() function to save the cut and resized image.

Guess you like

Origin blog.csdn.net/qq_60943902/article/details/129349689