为什么我无法在Python PIL中裁剪这张图片?(简单语法问题?)
from PIL import Image
im = Image.open(f) #the size is 500x350
box = (0,0,100,100)
kay = im.crop(box)
看起来这个没什么问题,对吧?
不过最后那一行会出错,程序会停止运行,但我不知道具体是什么错误,因为这是AJAX,我现在无法调试。
3 个回答
0
试着用整数坐标代替字符串:
from PIL import Image
im = Image.open(f) #the size is 500x350
box = (0,0,100,100)
kay = im.crop(box)
1
当你从AJAX的获取请求中拿到坐标时,它们是字符串格式的,你需要把它们转换成整数,这样裁剪操作才能成功。
4
如果你的控制器处理的是字符串,因为裁剪的数据是通过ajax GET请求传过来的,那么在进行裁剪之前,试着把这些字符串转换成整数可能会有帮助。下面是我在终端上看到的一个例子...
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'
>>>