本文整理汇总了Python中imghdr.what方法的典型用法代码示例。如果您正苦于以下问题:Python imghdr.what方法的具体用法?Python imghdr.what怎么用?Python imghdr.what使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类imghdr
的用法示例。
在下文中一共展示了imghdr.what方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload_image
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def upload_image(self, filename=None, filedata=None, tag=None):
token = self.auth.upload_token(self.bucket)
if filedata is None:
with open(filename, 'rb') as f:
filedata = f.read()
with BytesIO(filedata) as f:
ext = imghdr.what(f)
prefix = tag or "img"
name = "%s/%02x.%s" % (prefix, self.counter.incr(), ext)
ret, info = self.qiniu.put_data(token, name, filedata)
if ret is None:
return
return self.base_url + name
示例2: _get_extension
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def _get_extension(file):
"""
Gets the extension for the given file, which can be either a
str or an ``open()``'ed file (which has a ``.name`` attribute).
"""
if isinstance(file, str):
return os.path.splitext(file)[-1]
elif isinstance(file, pathlib.Path):
return file.suffix
elif isinstance(file, bytes):
kind = imghdr.what(io.BytesIO(file))
return ('.' + kind) if kind else ''
elif isinstance(file, io.IOBase) and not isinstance(file, io.TextIOBase) and file.seekable():
kind = imghdr.what(file)
return ('.' + kind) if kind is not None else ''
elif getattr(file, 'name', None):
# Note: ``file.name`` works for :tl:`InputFile` and some `IOBase`
return _get_extension(file.name)
else:
# Maybe it's a Telegram media
return get_extension(file)
示例3: get_image_type
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def get_image_type(imgname, imgdata=None):
imgtype = unicode_str(imghdr.what(pathof(imgname), imgdata))
# imghdr only checks for JFIF or Exif JPEG files. Apparently, there are some
# with only the magic JPEG bytes out there...
# ImageMagick handles those, so, do it too.
if imgtype is None:
if imgdata is None:
with open(pathof(imgname), 'rb') as f:
imgdata = f.read()
if imgdata[0:2] == b'\xFF\xD8':
# Get last non-null bytes
last = len(imgdata)
while (imgdata[last-1:last] == b'\x00'):
last-=1
# Be extra safe, check the trailing bytes, too.
if imgdata[last-2:last] == b'\xFF\xD9':
imgtype = "jpeg"
return imgtype
示例4: _get_mime_type
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def _get_mime_type(self, buff):
"""Get the MIME type for a given stream of bytes
:param buff: Stream of bytes
:type buff: bytes
:rtype: str
"""
if self._magic is not None:
return self._magic.id_buffer(buff)
else:
try:
return mimetypes.guess_type("f." + imghdr.what(0, buff))[0]
except (IOError, TypeError):
logging.warning(
"Couldn't detect content type of avatar image"
". Specify the 'contentType' parameter explicitly."
)
return None
示例5: image_mime_type
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def image_mime_type(data):
"""Return the MIME type of the image data (a bytestring).
"""
# This checks for a jpeg file with only the magic bytes (unrecognized by
# imghdr.what). imghdr.what returns none for that type of file, so
# _wider_test_jpeg is run in that case. It still returns None if it didn't
# match such a jpeg file.
kind = _imghdr_what_wrapper(data)
if kind in ['gif', 'jpeg', 'png', 'tiff', 'bmp']:
return 'image/{0}'.format(kind)
elif kind == 'pgm':
return 'image/x-portable-graymap'
elif kind == 'pbm':
return 'image/x-portable-bitmap'
elif kind == 'ppm':
return 'image/x-portable-pixmap'
elif kind == 'xbm':
return 'image/x-xbitmap'
else:
return 'image/x-{0}'.format(kind)
示例6: guess_extension
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def guess_extension(data):
# image type
typ = imghdr.what(None, h=data)
if typ == 'jpeg':
return 'jpg'
elif typ == 'xbm':
pass # some HLSL files are recognized as xbm
elif typ is not None:
return typ
# json
try:
json.loads(data)
return 'json'
except (json.JSONDecodeError, UnicodeDecodeError):
pass
# others
for prefix, ext in WadFileHeader._magic_numbers_ext.items():
if data.startswith(prefix):
return ext
示例7: test_has_validation_path
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def test_has_validation_path():
batch_size = 3
train_dataset = DummyHasValidation(subset="train",
batch_size=batch_size)
validation_dataset = DummyHasValidation(subset="validation",
batch_size=batch_size)
expected_train_image_dir = os.path.join(environment.DATA_DIR, DummyHasValidation.extend_dir)
expected_train_paths = [image_path for image_path in glob(os.path.join(expected_train_image_dir, "**/*"))
if os.path.isfile(image_path) and imghdr.what(image_path) in {"jpeg", "png"}]
assert len(expected_train_paths) == train_dataset.num_per_epoch
expected_validation_image_dir = os.path.join(environment.DATA_DIR, DummyHasValidation.validation_extend_dir)
expected_validation_paths = [image_path for image_path in glob(os.path.join(expected_validation_image_dir, "**/*"))
if os.path.isfile(image_path) and imghdr.what(image_path) in {"jpeg", "png"}]
assert len(expected_validation_paths) == validation_dataset.num_per_epoch
示例8: test_image_folder_onthefly
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def test_image_folder_onthefly():
Onthefly = type('Onthefly',
(ImageFolderBase,),
{"extend_dir": "dummy_classification", "validation_extend_dir": "open_images_v4"})
batch_size = 3
train_dataset = Onthefly(subset="train",
batch_size=batch_size)
validation_dataset = Onthefly(subset="validation",
batch_size=batch_size)
expected_train_image_dir = os.path.join(environment.DATA_DIR, DummyHasValidation.extend_dir)
expected_train_paths = [image_path for image_path in glob(os.path.join(expected_train_image_dir, "**/*"))
if os.path.isfile(image_path) and imghdr.what(image_path) in {"jpeg", "png"}]
assert len(expected_train_paths) == train_dataset.num_per_epoch
expected_validation_image_dir = os.path.join(environment.DATA_DIR, DummyHasValidation.validation_extend_dir)
expected_validation_paths = [image_path for image_path in glob(os.path.join(expected_validation_image_dir, "**/*"))
if os.path.isfile(image_path) and imghdr.what(image_path) in {"jpeg", "png"}]
assert len(expected_validation_paths) == validation_dataset.num_per_epoch
示例9: test_invoke
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def test_invoke(self):
helloWorld= 'test_invoke_hello_world_' + ''.join(random.choice(string.ascii_lowercase) for _ in range(8))
logging.info('create function: {0}'.format(helloWorld))
self.client.create_function(
self.serviceName, helloWorld,
handler='main.my_handler', runtime='python2.7', codeZipFile='test/hello_world/hello_world.zip')
r = self.client.invoke_function(self.serviceName, helloWorld)
self.assertEqual(r.data.decode('utf-8'), 'hello world')
self.client.delete_function(self.serviceName, helloWorld)
# read a image as invoke parameter.
imageProcess = 'test_invoke_nodejs_image_resize'
logging.info('create function: {0}'.format(imageProcess))
self.client.create_function(
self.serviceName, imageProcess,
handler='image_process.resize', runtime='nodejs4.4', codeDir='test/image_process/code')
sourceImage = open('test/image_process/data/serverless.png', 'rb')
destImage = open('/tmp/serverless.png', 'wb')
r = self.client.invoke_function(self.serviceName, imageProcess, payload=sourceImage)
destImage.write(r.data)
sourceImage.close()
destImage.close()
self.assertEqual(imghdr.what('/tmp/serverless.png'), 'png')
self.client.delete_function(self.serviceName, imageProcess)
示例10: test_plot
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def test_plot(self):
""" Test a simple plot.
Complex to test anything. Just check that there is no exception. """
from supvisors.plot import StatisticsPlot
from supvisors.viewimage import StatsImage
plot = StatisticsPlot()
self.assertEqual({}, plot.ydata)
# add series of data
plot.add_plot('dummy_title_1', 'unit_1', [1, 2, 3])
plot.add_plot('dummy_title_2', 'unit_2', [10, 20, 30])
self.assertDictEqual({('dummy_title_1', 'unit_1'): [1, 2, 3], ('dummy_title_2', 'unit_2'): [10, 20, 30]}, plot.ydata)
# export image in buffer
contents = StatsImage()
plot.export_image(contents)
# test that result is a PNG file
self.assertEqual('png', imghdr.what('', h=contents.contents.getvalue()))
示例11: get_img
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def get_img(self, fnames):
"""
:params fnames: possible file paths
:returns: two base64 jpg string
"""
fnames = [k for k in fnames if k] # filter out empty string
big_file, small_file = self._get_img_file(fnames)
def get_jpg_b64(img_file):
if not img_file:
return None
if not img_file.endswith('jpg') and \
imghdr.what(img_file) != 'jpeg':
im = Image.open(open(img_file, 'rb'))
buf = io.BytesIO()
im.convert('RGB').save(buf, 'JPEG', quality=JPEG_QUALITY)
return base64.b64encode(buf.getvalue()).decode('ascii')
return get_file_b64(img_file)
big_file = get_jpg_b64(big_file)
if big_file:
return big_file
return get_jpg_b64(small_file)
示例12: send_photo
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def send_photo(self, target, photo_data, sender=None):
ft = imghdr.what('', photo_data)
if ft is None:
return
filename = "image." + ft
data_io = io.BytesIO(photo_data)
roomid = wxRoomNicks[target]
if sender is not None:
itchat.send(msg="{} sent a photo...".format(sender), toUserName=roomid)
itchat.send_image(fileDir=filename, toUserName=roomid, file_=data_io)
示例13: send_photo
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def send_photo(self, target, photo_data, sender=None):
api = self.api_base + "/sendPhoto"
caption = "{} sent a photo".format(sender) if sender else ""
ft = imghdr.what('', photo_data)
if ft is None:
return
filename = "image." + ft
data = {'chat_id': target, 'caption': caption}
files = {'photo': (filename, photo_data)}
self._must_post(api, data=data, files=files)
示例14: __init__
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def __init__(self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, **_params):
"""Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
_subtype = imghdr.what(None, _imagedata)
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
MIMENonMultipart.__init__(self, 'image', _subtype, **_params)
self.set_payload(_imagedata)
_encoder(self)
示例15: chunks
# 需要导入模块: import imghdr [as 别名]
# 或者: from imghdr import what [as 别名]
def chunks(iterable, size=100):
"""
Turns the given iterable into chunks of the specified size,
which is 100 by default since that's what Telegram uses the most.
"""
it = iter(iterable)
size -= 1
for head in it:
yield itertools.chain([head], itertools.islice(it, size))