使用imghdr模块判断图片文件类型的实例
发布时间:2023-12-29 08:56:44
imghdr模块提供了一个函数imghdr.what(),可以用于判断图片文件的类型。它接收一个文件对象作为参数,并返回文件的类型。
下面是一个使用imghdr模块的实例,通过判断文件类型来确定是否为图片文件:
import imghdr
def check_image_file(file_path):
with open(file_path, "rb") as file:
file_type = imghdr.what(file)
if file_type:
print(f"{file_path} is a {file_type.upper()} file.")
else:
print(f"{file_path} is not a valid image file.")
# 示例图片文件路径
file_path_1 = "image.jpg"
file_path_2 = "image.png"
file_path_3 = "image.gif"
file_path_4 = "image.txt"
# 检查图片文件类型
check_image_file(file_path_1)
check_image_file(file_path_2)
check_image_file(file_path_3)
check_image_file(file_path_4)
这个例子中,首先导入了imghdr模块。然后,定义了一个check_image_file()函数,接收一个文件路径作为参数。
在check_image_file()函数中,使用open()函数打开文件,以二进制模式读取文件内容。然后,调用imghdr模块的what()函数,并传入打开的文件对象作为参数,以获取文件类型。
如果what()函数返回一个有效的文件类型,通过字符串的upper()方法将其转换为大写形式,并打印文件路径和文件类型。否则,打印文件路径和“not a valid image file”的提示。
最后,使用多个不同类型的文件路径调用check_image_file()函数,以测试不同类型的文件。在本例中,前三个文件路径分别是正确的图片文件路径,最后一个文件路径是一个普通的文本文件路径。
执行上述代码后,输出结果如下:
image.jpg is a JPEG file. image.png is a PNG file. image.gif is a GIF file. image.txt is not a valid image file.
可以看到,前三个文件是图片文件,而最后一个文件是一个普通的文本文件。通过imghdr模块的what()函数,我们可以轻松地判断图片文件的类型。
