Python PIL正在获取目录而不是图像

时间:2014-07-26 12:17:24

标签: python-2.7 python-imaging-library

这是我正在查看的一些代码,它的作用是将zip解压缩到临时目录,然后使用Pil“Image.open”来访问提取的文件。

import os
import re
import shutil
import zipfile
import tempfile
from natsort import natsorted
from epubpack import epubpack
from PIL import Image
import uuid

def cbz2epub3(cbzfname, epubfile='out.eub', tmpldir='template', mangamode=False, singlepage=False):
# working dir
imgdir = tempfile.mkdtemp()
workdir = tempfile.mkdtemp()
# convert
img_files = importImageFromZip(cbzfname, imgdir, mangamode=mangamode, singlepage=singlepage)
title = guessTitle(cbzfname)
ttbl = genTemplateInfo(img_files, title, mangamode=mangamode)
epubMakeTree(tmpldir, workdir, ttbl)
for fname in os.listdir(imgdir):
    shutil.move(os.path.join(imgdir, fname), os.path.join(workdir, 'EPUB', 'Image'))
epubpack(workdir, epubfile)
# cleanup
os.rmdir(imgdir)
shutil.rmtree(workdir)

def importImageFromZip(cbzfname, outdir, mangamode=False, singlepage=False):
# extract
cbz = zipfile.ZipFile(cbzfname,'r')
fnames = cbz.namelist()
cbz.extractall(outdir)
cbz.close()
# change name
print "Src images: %d" % len(fnames)
nlenw = len(str(len(fnames)))
new_fnames = []
idx = 0
for fname in natsorted(fnames):
    ext = os.path.splitext(fname)[1]
    src = os.path.join(outdir, fname)
    if fname == 'Thumbs.db':
        os.remove(src)
        continue
    idx += 1
    im = Image.open(src)

但它错误地说“src”是一个目录,但我读到os.path.join会给出文件名。

Traceback (most recent call last):
File "gui.py", line 40, in OnDropFiles
output = cbz2epub3( filename, epubname, mangamode=mangamode, singlepage=singlepage )
File "/home/dave/Documents/cbz2epub3-master/cbz2epub3.py", line 33, in cbz2epub3
img_files = importImageFromZip(cbzfname, imgdir, mangamode=mangamode, singlepage=singlepage)
File "/home/dave/Documents/cbz2epub3-master/cbz2epub3.py", line 62, in importImageFromZip
im = Image.open(src)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1996, in open
fp = builtins.open(fp, "rb")
IOError: [Errno 21] Is a directory: '/tmp/tmpjsosRY/test/

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您的zip文件中看起来有一个名为/test的文件夹。 作为快速解决方法,您可以在致电src之前检查Image.open(src)路径是否为文件。

...
src = os.path.join(outdir, fname)
if not os.path.isfile(src):
    continue
if fname == 'Thumbs.db':
    os.remove(src)
    continue
idx += 1
im = Image.open(src)