在 Python 中确定图像的类型?

pythonserver side programmingprogramming更新于 2025/5/14 19:24:17

在本节中,我们将了解我们拥有的图像文件的类型。因此,考虑这样一种情况,在目录中我们有数百个图像文件,并且我们想要获取所有 jgeg(或任何特定图像文件类型)文件类型。我们将使用 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])

其中

  • Filename:测试 filename 文件中包含的图像数据,并返回描述图像类型的字符串。

  • h:它是可选的,如果 h 存在,则忽略文件名,并假定 h 包含要测试的字节流。

以下是使用 imghdr 包识别的允许图像类型。

Value
Image format
'rgb'
SGI ImgLib Files
'gif'
GIF 87a and 89a Files
'pbm'
Portable Bitmap Files
'pgm'
Portable Graymap Files
'ppm'
Portable Pixmap Files
'tiff'
TIFF Files
'rast'
Sun Raster Files
'xbm'
X Bitmap Files
'jpeg'
JPEG data in JFIF or Exif formats
'bmp'
BMP files
'png'
Portable Network Graphics

但是我们可以通过附加到此变量来扩展 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))

相关文章


有用资源