我想了解 Pillow
库中的 verify()
函数是如何实现的。在源代码中我只发现了这个:
def verify(self):
"""
Verifies the contents of a file. For data read from a file, this
method attempts to determine if the file is broken, without
actually decoding the image data. If this method finds any
problems, it raises suitable exceptions. If you need to load
the image after using this method, you must reopen the image
file.
"""
pass
在哪里可以找到实现?
(我在这里找到的源代码:Pillow source code)
最佳答案
一个comment on GitHub解释:
Image.[v]erify only checks the chunk checksums in png files, and is a no-op elsewhere.
所以简短的答案是,您已经找到了绝对不执行任何操作的默认实现。
PNG 文件除外,您可以在 PngImageFile.verify
中找到其实现。方法:
def verify(self):
"Verify PNG file"
if self.fp is None:
raise RuntimeError("verify must be called directly after open")
# back up to beginning of IDAT block
self.fp.seek(self.tile[0][2] - 8)
self.png.verify()
self.png.close()
self.fp = None
然后通过self.png.verify()
调用ChunkStream.verify
:
def verify(self, endchunk=b"IEND"):
# Simple approach; just calculate checksum for all remaining
# blocks. Must be called directly after open.
cids = []
while True:
cid, pos, length = self.read()
if cid == endchunk:
break
self.crc(cid, ImageFile._safe_read(self.fp, length))
cids.append(cid)
return cids
更详细的源代码分割
您已经引用的 verify
代码Image
的方法类显示它默认不执行任何操作:
class Image:
...
def verify(self):
"""
Verifies the contents of a file. For data read from a file, this
method attempts to determine if the file is broken, without
actually decoding the image data. If this method finds any
problems, it raises suitable exceptions. If you need to load
the image after using this method, you must reopen the image
file.
"""
pass
但对于 PNG 文件,默认的 verify
方法会被覆盖,如 ImageFile
的源代码所示。类,继承自 Image
类:
class ImageFile(Image.Image):
"Base class for image file format handlers."
...
以及PNG插件类的源代码PngImageFile
它继承自ImageFile
:
##
# Image plugin for PNG images.
class PngImageFile(ImageFile.ImageFile):
...
并重写了 verify
的实现:
def verify(self):
"Verify PNG file"
if self.fp is None:
raise RuntimeError("verify must be called directly after open")
# back up to beginning of IDAT block
self.fp.seek(self.tile[0][2] - 8)
self.png.verify()
self.png.close()
self.fp = None
然后通过self.png.verify()
调用ChunkStream.verify
:
def verify(self, endchunk=b"IEND"):
# Simple approach; just calculate checksum for all remaining
# blocks. Must be called directly after open.
cids = []
while True:
cid, pos, length = self.read()
if cid == endchunk:
break
self.crc(cid, ImageFile._safe_read(self.fp, length))
cids.append(cid)
return cids
通过PngStream
不覆盖 verify
的类:
class PngStream(ChunkStream):
...
关于python - 验证功能是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39637629/