使用Python Pillow裁剪图像

49

我安装了Python的Pillow库,并尝试裁剪图片。

其他效果都很好(例如,缩略图、模糊图像等)。

每当我运行下面的代码时,都会收到以下错误:

tile cannot extend outside image

test_image = test_media.file
original = Image.open(test_image)

width, height = original.size   # Get dimensions
left = width/2
top = height/2
right = width/2
bottom = height/2
cropped_example = original.crop((left, top, right, bottom))

cropped_example.show()

我使用了一个在PIL中找到的裁剪示例,因为我无法为Pillow找到类似的(我认为应该是相同的)。


1
可能是 https://dev59.com/EXNA5IYBdhLWcg3wI6R4 的重复问题。 - xor
2个回答

85
问题出在逻辑上,而不是Pillow库。Pillow库几乎100%兼容PIL库。您创建了一个大小为0x0的图像(left = right& top = bottom)。没有任何显示设备可以显示这样的图像。以下是我的代码。
from PIL import Image

test_image = "Fedora_19_with_GNOME.jpg"
original = Image.open(test_image)
original.show()

width, height = original.size   # Get dimensions
left = width/4
top = height/4
right = 3 * width/4
bottom = 3 * height/4
cropped_example = original.crop((left, top, right, bottom))

cropped_example.show()

很可能这不是你想要的。但这应该引导你对应该做什么有一个清晰的想法。


22
如果有人想知道这个是干什么的,它会剪切掉图像外部的边缘,只留下原始图像的中心部分。裁剪后的图像尺寸将是原始图像尺寸的一半。以下是一个例子:如果你要裁剪的图像大小是100 x 100,lefttop都将被设置为25rightbottom都将被设置为75。因此,你最终会得到一个50 x 50的图像,它将是原始图像的精确中心部分。 - Nick

11

Python Pillow 图像裁剪代码:

img2 = img.crop((200, 330, 730, 606)) # (left, top, right, bottom)

但是,那些匆忙或像我这样愚蠢的人 - 这里有一个抽象:)

Python Pillow 坐标系统抽象


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接