當前位置: 首頁>>代碼示例>>Python>>正文


Python imghdr.what方法代碼示例

本文整理匯總了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 
開發者ID:tuna,項目名稱:fishroom,代碼行數:19,代碼來源:filestore.py

示例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) 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:23,代碼來源:utils.py

示例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 
開發者ID:BasioMeusPuga,項目名稱:Lector,代碼行數:21,代碼來源:mobi_cover.py

示例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 
開發者ID:pycontribs,項目名稱:jira,代碼行數:22,代碼來源:client.py

示例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) 
開發者ID:beetbox,項目名稱:mediafile,代碼行數:22,代碼來源:mediafile.py

示例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 
開發者ID:CommunityDragon,項目名稱:CDTB,代碼行數:23,代碼來源:wad.py

示例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 
開發者ID:blue-oil,項目名稱:blueoil,代碼行數:21,代碼來源:test_image_folder.py

示例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 
開發者ID:blue-oil,項目名稱:blueoil,代碼行數:25,代碼來源:test_image_folder.py

示例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) 
開發者ID:aliyun,項目名稱:fc-python-sdk,代碼行數:27,代碼來源:function_test.py

示例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())) 
開發者ID:julien6387,項目名稱:supvisors,代碼行數:18,代碼來源:test_plot.py

示例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) 
開發者ID:ppwwyyxx,項目名稱:wechat-dump,代碼行數:25,代碼來源:res.py

示例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) 
開發者ID:tuna,項目名稱:fishroom,代碼行數:12,代碼來源:wechat.py

示例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) 
開發者ID:tuna,項目名稱:fishroom,代碼行數:14,代碼來源:telegram.py

示例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) 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:30,代碼來源:image.py

示例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)) 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:11,代碼來源:utils.py


注:本文中的imghdr.what方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。