为什么Python图像中的PIL不能裁剪?(简单的语法问题?)

2024-05-15 20:01:52 发布

您现在位置:Python中文网/ 问答频道 /正文

from PIL import Image

im = Image.open(f)  #the size is 500x350
box = (0,0,100,100)
kay = im.crop(box)

看来这没什么不对吧?在

最后一行将导致一个错误并且不会继续,但是我不知道错误是什么,因为它是AJAX,我不能调试ATM。在


Tags: thefromcropimageimportboxsizepil
3条回答

如果您的控制器正在处理字符串,因为裁剪数据是通过ajaxget传入的,那么在应用裁剪之前,最好尝试将它们变成整数。我终端的例子。。。在

Trinity:~ kelvin$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) 
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
>>> f = open("happy.jpg")
>>> im = Image.open(f)
>>> box = (0,0,100,100)
>>> kay = im.crop(box)
>>> kay
<PIL.Image._ImageCrop instance at 0xb1ea80>
>>> bad_box = ("0","0","100","100")
>>> nkay = im.crop(bad_box)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PIL/Image.py", line 742, in crop
    return _ImageCrop(self, box)
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PIL/Image.py", line 1657, in __init__
    self.size = x1-x0, y1-y0
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>> 

尝试使用整数坐标而不是字符串:

from PIL import Image

im = Image.open(f) #the size is 500x350 
box = (0,0,100,100) 
kay = im.crop(box)

当您从ajaxget请求获取坐标时,它们是字符串,您必须将它们解析为Int,以便裁剪成功。在

相关问题 更多 >