def process_images(self, docname, doctree):
"""Process and rewrite image URIs."""
for node in doctree.traverse(nodes.image):
# Map the mimetype to the corresponding image. The writer may
# choose the best image from these candidates. The special key * is
# set if there is only single candidate to be used by a writer.
# The special key ? is set for nonlocal URIs.
node['candidates'] = candidates = {}
imguri = node['uri']
if imguri.find('://') != -1:
self.warn_node('nonlocal image URI found: %s' % imguri, node)
candidates['?'] = imguri
continue
rel_imgpath, full_imgpath = self.relfn2path(imguri, docname)
# set imgpath as default URI
node['uri'] = rel_imgpath
if rel_imgpath.endswith(os.extsep + '*'):
for filename in glob(full_imgpath):
new_imgpath = relative_path(path.join(self.srcdir, 'dummy'),
filename)
if filename.lower().endswith('.pdf'):
candidates['application/pdf'] = new_imgpath
elif filename.lower().endswith('.svg'):
candidates['image/svg+xml'] = new_imgpath
else:
try:
f = open(filename, 'rb')
try:
imgtype = imghdr.what(f)
finally:
f.close()
except (OSError, IOError) as err:
self.warn_node('image file %s not readable: %s' %
(filename, err), node)
if imgtype:
candidates['image/' + imgtype] = new_imgpath
else:
candidates['*'] = rel_imgpath
# map image paths to unique image names (so that they can be put
# into a single directory)
for imgpath in itervalues(candidates):
self.dependencies.setdefault(docname, set()).add(imgpath)
if not os.access(path.join(self.srcdir, imgpath), os.R_OK):
self.warn_node('image file not readable: %s' % imgpath,
node)
continue
self.images.add_file(docname, imgpath)
评论列表
文章目录