python判断图像是否正常_在Python中检测文件是否是图像

假设:>>> files = {"a_movie.mkv", "an_image.png", "a_movie_without_extension", "an_image_without_extension"}

它们是脚本文件夹中合适的电影和图像文件。

您可以使用内置的mimetypes模块,但如果没有扩展,它将无法工作。>>> import mimetypes

>>> {file: mimetypes.guess_type(file) for file in files}

{'a_movie_without_extension': (None, None), 'an_image.png': ('image/png', None), 'an_image_without_extension': (None, None), 'a_movie.mkv': (None, None)}

或者调用unix命令file。这在没有扩展名的情况下工作,但在Windows中不行:>>> import subprocess

>>> def find_mime_with_file(path):

... command = "/usr/bin/file -i {0}".format(path)

... return subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).communicate()[0].split()[1]

...

>>> {file: find_mime_with_file(file) for file in files}

{'a_movie_without_extension': 'application/octet-stream;', 'an_image.png': 'image/png;', 'an_image_without_extension': 'image/png;', 'a_movie.mkv': 'application/octet-stream;'}

或者尝试使用PIL打开它,并检查是否有错误,但需要安装PIL:>>> from PIL import Image

>>> def check_image_with_pil(path):

... try:

... Image.open(path)

... except IOError:

... return False

... return True

...

>>> {file: check_image_with_pil(file) for file in files}

{'a_movie_without_extension': False, 'an_image.png': True, 'an_image_without_extension': True, 'a_movie.mkv': False}

或者,为了简单起见,正如你所说,只需检查扩展,这是我认为最好的方法。>>> extensions = {".jpg", ".png", ".gif"} #etc

>>> {file: any(file.endswith(ext) for ext in extensions) for file in files}

{'a_movie_without_extension': False, 'an_image.png': True, 'an_image_without_extension': False, 'a_movie.mkv': False}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值