使用Python PIL库裁剪和保存图像时遇到问题

48 投票
2 回答
52486 浏览
提问于 2025-04-15 12:38

我正在尝试裁剪一张分辨率很高的图片,并保存裁剪后的结果,以确保操作完成。但是无论我怎么使用保存的方法,我总是遇到以下错误:SystemError: tile cannot extend outside image

from PIL import Image

# size is width/height
img = Image.open('0_388_image1.jpeg')
box = (2407, 804, 71, 796)
area = img.crop(box)

area.save('cropped_0_388_image1', 'jpeg')
output.close()

2 个回答

15

试试这个:

这是一个简单的代码,用来裁剪图片,效果非常好哦;)

import Image

def crop_image(input_image, output_image, start_x, start_y, width, height):
    """Pass input name image, output name image, x coordinate to start croping, y coordinate to start croping, width to crop, height to crop """
    input_img = Image.open(input_image)
    box = (start_x, start_y, start_x + width, start_y + height)
    output_img = input_img.crop(box)
    output_img.save(output_image +".png")

def main():
    crop_image("Input.png","output", 0, 0, 1280, 399)

if __name__ == '__main__': main()

在这个例子中,输入的图片大小是1280 x 800像素,裁剪后的图片大小是1280 x 399像素,从左上角开始裁剪。

69

这个框的坐标是(左,上,右,下),所以你可能是想说(2407, 804, 2407+71, 804+796)?

编辑:这四个坐标都是从左上角开始测量的,表示从这个角落到左边缘、上边缘、右边缘和下边缘的距离。

你的代码应该像这样,才能从位置2407,804获取一个300x200的区域:

left = 2407
top = 804
width = 300
height = 200
box = (left, top, left+width, top+height)
area = img.crop(box)

撰写回答