确定Python中图像的类型?
在本节中,我们将看到图像文件的类型。因此,请请看以下情况:目录中有数百个图像文件,并且我们希望获取所有jgeg(或任何特定的图像文件类型)文件类型。我们将使用python以编程方式完成所有这些工作。
Python提供了确定图像类型的库,该库上的图像是imghdr。
pythonimghdr软件包确定文件或字节流中包含的图像类型。
安装
如果您使用的是python3.6或更高版本,则很有可能imghdr模块是标准软件包,并且将随python安装一起提供。
要在计算机上安装imghdr,只需在命令终端中的以下命令中运行:
pip install imghdr
成功安装后,要验证imghdr是否已正确安装,不只是将模块导入pythonshell中即可。
>>> import imghdr >>>
如果没有错误,则意味着imghdr已安装在您的计算机中。
语法
imghdr软件包定义了以下功能:
imghdr.what(filename[, h])
哪里
Filename:测试文件名中包含的图像数据,并返回描述图像类型的字符串。
h:它是可选的,如果h存在,则忽略文件名,并假定h包含要测试的字节流。
以下是使用imghdr软件包识别的允许的图像类型。
但是我们可以通过附加到此变量来扩展imghdr软件包可以识别的文件类型列表。
免疫测试
该功能包含执行各个测试的功能列表。每个函数都有两个参数:字节流和一个类似文件的打开对象。但是,当what()
用字节流调用时,类似文件的对象将为None。
测试函数将以字符串形式返回图像类型,否则返回无。
>>> import imghdr >>> imghdr.what('clock.jpg') 'jpeg'
以下只是imghdr软件包的一种实现,其中,如果存在某些特定的imagefile扩展名,请执行特定的操作:
def identify_filetype(url, imageName, folderName): session = _setupSession() try: # time out is another parameter tuned image = session.get(url, timeout = 5) with open(os.path.join(folderName, imageName),'wb') as fout: fout.write(image.content) fileExtension = imghdr.what(os.path.join(folderName, imageName)) if fileExtension is None: os.remove(os.path.join(folderName, imageName)) else: newName = imageName + '.' + str(fileExtension) os.rename(os.path.join(folderName, imageName), os.path.join(folderName, newName)) except Exception as e: print ("failed to download one pages with url of " + str(url))