我正试图在python中制作一个简单的函数,它可以接收文件路径和输出文件路径,然后为在文件路径中找到的图像制作一个64x64缩略图,并将缩略图保存到输出文件路径。这是我的全部代码:
def create_thumbnail2(filepath, outputpath):
if not os.path.exists(filepath):
print "Input file path for create_thumbnail doesn't exist. Returning None"
return None
try:
size = 64, 64 #Will be making a 64x64 thumbnail
im = Image.open(filepath)
print "image successfully opened"
im.thumbnail(size, Image.ANTIALIAS)
print "made thumbnail"
im.save(outputpath, "PNG") #Save image as a PNG
return outputpath
except IOError:
print "I/O error"
return None
print "TEST 1"
filep = "test_images/cat1.jpg"
print create_thumbnail2(filep, "test_images/cat1_thumbnail.png")
print "nTEST 2"
filep = "test_images/cat2.jpg"
print create_thumbnail2(filep, "test_images/cat2_thumbnail.png")
问题是,这段代码对某些图像可以很好地工作,但会在我调用"im.thrumbia(size,Image.ANTIALIAS)"的行上引发IOError。这是上面程序的输出。
TEST 1
image successfully opened
I/O error
None
TEST 2
image successfully opened
made thumbnail
test_images/cat2_thumbnail.png
您会注意到,在第一个测试中,在打开图像之后但创建缩略图之前,会抛出一个I/O错误。在第二个测试中,没有抛出任何错误,缩略图实际上已成功保存到outputpath。无论我按什么顺序调用两个不同的测试,或者如果我注释掉其中一个并单独运行另一个,结果总是测试1失败,测试2成功。cat1.jpg和cat2.jpg似乎都是有效的JPEG图像,除了文件名和实际图片内容之外,我真的找不到它们之间的任何不同。
如果有人想用我的图片试试,我从这里下载了cat1:http://dellone2one.com/wp-content/uploads/2009/11/angry_wet_cat.jpg
我从这里下载了cat2:http://cvcl.mit.edu/hybrid/cat2.jpg
编辑以添加完整的回溯而不进行处理:这是完整的回溯
Traceback (most recent call last):
File "image_utils.py", line 75, in <module>
print create_thumbnail2(filep, "test_images/cat1_thumbnail.png")
File "image_utils.py", line 66, in create_thumbnail2
im.thumbnail(size, Image.ANTIALIAS)
File "/Users/dylan/arcode/python/arcode/PIL/Image.py", line 1559, in thumbnail
self.load()
File "/Users/dylan/arcode/python/arcode/PIL/ImageFile.py", line 189, in load
d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
File "/Users/dylan/arcode/python/arcode/PIL/Image.py", line 385, in _getdecoder
raise IOError("decoder %s not available" % decoder_name)
IOError: decoder jpeg not available
我的PIL安装也是如此。(PIL 1.1.7、Py 2.6、OSX 10.6)
编辑:啊-在不同的OSX机器上安装可以工作。我知道在OSX上使用JPG支持构建PIL存在问题,但我记不起这两个安装的来源,所以我不能告诉你如何修复它。
编辑2:我最记得的是,用这里的说明建造PIL产生了工作装置。构建和安装命令必须运行sudo,并且必须手动修改gcc的三次调用,以删除"-arch-ppc"选项并重新运行。
这是建立PIL的另一条途径。