如何从类似文件的对象中python mimetypes.guess_type [英] how to python mimetypes.guess_type from a file-like object

查看:122
本文介绍了如何从类似文件的对象中python mimetypes.guess_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> mimetypes.guess_type('picture.jpg')
('image/jpeg', None)

现在我有一个类似文件的对象(例如stingIO), 哪些内容是图像数据

Now I have a file-like object, (eg. stingIO), which content is image's data

如何从类似文件的对象中检测出模仿类型

How can i detect the mimetypes from a file-like object

推荐答案

python mimetype标准模块将文件名映射为mime-type,反之亦然.要使用它,您需要一个文件名或一个mime类型,在这种情况下,它将带给您可能的文件扩展名.

The python mimetype standard module maps filenames to mime-types and vice versa. To use it, you'll need a filename or a mime-type, in which case it'll give you back a possible file extension.

它不会/不会根据文件的内容确定MIME类型.您需要另一种工具来执行此操作. unix file命令背后的库Libmagic是这些工具之一. filemagic模块( https://pypi.python.org/pypi/filemagic/1.6)是libmagic的python接口.

It won't/doesn't determine the mime-type based on a file's contents. You need another type of tool to do that. Libmagic, the library behind the unix file command, is one of those tools. The filemagic module (https://pypi.python.org/pypi/filemagic/1.6) is a python interface to libmagic.

import urllib2
import magic

img_data = urllib2.urlopen('https://www.google.com/images/srpr/logo11w.png').read()
# You can add flags 
# magic.Magic(flags=magic.MAGIC_MIME_TYPE) for take "/image/png"
m = magic.Magic()
print m.id_buffer(img_data)
m.close()

这篇关于如何从类似文件的对象中python mimetypes.guess_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆