如何修复在PIL创建文件路径缩略图时出现的IOError

2 投票
1 回答
1117 浏览
提问于 2025-04-16 19:38

我正在尝试用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.thumbnail(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

你会注意到,在第一次测试中,打开图片后就抛出了一个输入输出错误,但在创建缩略图之前就出错了。在第二次测试中没有错误抛出,缩略图实际上成功保存到了输出路径。不管我以什么顺序调用这两个不同的测试,或者我注释掉一个只运行另一个,结果总是第一次测试失败,第二次测试成功。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

1 个回答

1

我安装的PIL也出现了同样的问题。(PIL 1.1.7,Python 2.6,OSX 10.6)

补充说明:
哦,另一台OSX机器上的安装是可以正常工作的。我知道在OSX上安装PIL时,支持JPG格式会有一些问题,但我记不清这两个安装的来源是什么,所以无法告诉你怎么解决。

补充说明2:
我记得大概是按照这里的说明来安装PIL的,结果是成功的。安装和构建的命令需要用sudo来运行,而且有三次调用gcc的地方需要手动修改,去掉“-arch ppc”这个选项,然后重新运行。

还有另一种方法来安装PIL。

撰写回答