Python Pillow 简明教程

Python Pillow - Identifying Image Files

使用 Python Pillow (PIL) 库识别图像文件涉及检查文件扩展名以确定文件是否可能为图像。虽然 Pillow 本身没有用于识别图像文件的内置方法,但我们可以使用 os 模块的函数(例如 listdir(), path.splitext(), path.is_image_file(), path.join() )根据用户要求基于其扩展名来过滤文件。

Python 的 os.path 模块没有提供直接 is_image_file() 函数来识别图像文件。相反,我们通常可以使用 Pillow 库 (PIL) 来检查文件是否为图像。

但是,我们可以使用 os.path 结合 Pillow 创建一个自定义的 is_image_file() 函数,以根据其扩展名检查文件是否看起来像图像。

以下是如何使用 os.path 检查文件扩展名并判断文件是否可能是图像文件的示例−

  1. 我们定义 is_image_file() 函数,它首先检查文件的扩展名是否似乎是常见的图像格式(在“image_extensions”中定义)。如果不识别文件扩展名,则假定它不是图像文件。

  2. 对于识别的图像文件扩展名,该函数尝试使用 Pillow 的 Image.open() 将文件作为图像打开。如果此操作成功且没有错误,则该函数返回 True ,表示该文件是有效的图像。

  3. 如果在打开文件时出现问题,该函数将返回 False

  4. 此方法结合 os.path 来提取文件扩展名和 Pillow 来检查文件是否为有效的图像。

Example

import os
from PIL import Image
def is_image_file(file_path):
   image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".ico"}
#Add more extensions as needed
   _, file_extension = os.path.splitext(file_path)

#Check if the file extension is in the set of image extensions
    return file_extension.lower() in image_extensions
file_path = "Images/butterfly.jpg"
if is_image_file(file_path):
   print("This is an image file.")
   Image.open(file_path)
else:
   print("This is not an image file.")

Output

This is an image file.

Example

在此示例中,我们会将文件扩展名作为 pdf 传递,因为它不是图像文件扩展名,因此结果将不是图像文件。

import os
from PIL import Image
def is_image_file(file_path):
   image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".ico"}
#Add more extensions as needed
   _, file_extension = os.path.splitext(file_path)

#Check if the file extension is in the set of image extensions
   return file_extension.lower() in image_extensions
file_path = "Images/butterfly.pdf"
if is_image_file(file_path):
   print("This is an image file.")
   Image.open(file_path)
else:
   print("This is not an image file.")

Output

This is not an image file.