在 Python 中确定图像类型?
在本节中,我们将了解我们拥有的图像文件的类型。所以,考虑一种情况,在一个目录中我们有数百个图像文件,我们想要获取所有 jpeg(或任何特定图像文件类型)的文件类型。所有这些我们都将使用 Python 以编程方式完成。
Python 提供库来确定图像类型,其中一个库是 imghdr。
Python 的 imghdr 包确定文件中或字节流中包含的图像类型。
安装
如果您使用的是 Python 3.6 或更高版本,则 imghdr 模块是一个标准包,并将随 Python 安装一起提供。可能性非常大。
要在您的机器上安装 imghdr,只需在您的命令终端中运行以下命令:
pip install imghdr
安装成功后,要验证 imghdr 是否已正确安装,只需在您的 Python shell 中导入该模块。
>>> import imghdr >>>
如果您没有收到任何错误,则表示 imghdr 已安装在您的机器上。
语法
imghdr 包定义了以下函数:
imghdr.what(filename[, h])
其中
**文件名**:测试文件名指定的图像数据,并返回一个字符串,描述图像类型。
**h**:这是可选的,如果存在 h,则忽略文件名,并假定 h 包含要测试的字节流。
以下是使用 imghdr 包识别的允许的图像类型。
| 值 | 图像格式 |
|---|---|
| 'rgb' | SGI ImgLib 文件 |
| 'gif' | GIF 87a 和 89a 文件 |
| 'pbm' | 便携式位图文件 |
| 'pgm' | 便携式灰度图文件 |
| 'ppm' | 便携式像素图文件 |
| 'tiff' | TIFF 文件 |
| 'rast' | Sun 光栅文件 |
| 'xbm' | X 位图文件 |
| 'jpeg' | JFIF 或 Exif 格式的 JPEG 数据 |
| 'bmp' | BMP 文件 |
| 'png' | 便携式网络图形 |
但是我们可以通过附加到此变量来扩展 imghdr 包可以识别的文件类型列表。
imghdr.tests
此函数包含执行各个测试的函数列表。每个函数都接受两个参数:字节流和一个类似文件的打开对象。但是,当使用字节流调用 what() 时,类似文件的对象将为 None。
测试函数将返回图像类型作为字符串,如果失败则返回 None。
>>> import imghdr
>>> imghdr.what('clock.jpg')
'jpeg'下面只是一个 imghdr 包的实现示例,如果存在某些特定的图像文件扩展名,则执行特定操作。
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))
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP