Python imghdr 模块,what() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用imghdr.what()

项目:imageDownloader    作者:whcacademy    | 项目源码 | 文件源码
def _download(args):
    url, folderName, index = args
    session = setupSession()
    try:
        # time out is another parameter tuned
        # fit for the network about 10Mb
        image = session.get(url, timeout = 5)
        imageName = str(index)
        with open(os.path.join(folderName, imageName),'wb') as fout:
            fout.write(image.content)
        fileExtension = imghdr.what(os.path.join(folderName, imageName))
        if fileExtension is None:
            os.remove(os.path.join(folderName, imageName))
        else:
            newName = imageName + '.' + str(fileExtension)
            os.rename(os.path.join(folderName, imageName), os.path.join(folderName, newName))

    except Exception as e:
        print ("failed to download one pages with url of " + str(url))

# basic funciton to get id list
项目:imageDownloader    作者:whcacademy    | 项目源码 | 文件源码
def _download(url, imageName, folderName):
    session = _setupSession()
    try:
        # time out is another parameter tuned
        # fit for the network about 10Mb
        image = session.get(url, timeout = 5)
        with open(os.path.join(folderName, imageName),'wb') as fout:
            fout.write(image.content)
        fileExtension = imghdr.what(os.path.join(folderName, imageName))
        if fileExtension is None:
            os.remove(os.path.join(folderName, imageName))
        else:
            newName = imageName + '.' + str(fileExtension)
            os.rename(os.path.join(folderName, imageName), os.path.join(folderName, newName))

    except Exception as e:
        print ("failed to download one pages with url of " + str(url))

# wrapper for map function
项目:Automatic-Image-Colorization    作者:Armour    | 项目源码 | 文件源码
def init_file_path(directory):
    """
    Get the image file path array
    :param directory: the directory that store images
    :return: an array of image file path
    """
    paths = []

    if not debug:
        print "Throwing all gray space images now... this may takes some time.."

    for file_name in os.listdir(directory):
        # Skip files that is not jpg
        file_path = '%s/%s' % (directory, file_name)
        if not file_name.endswith('.jpg') or imghdr.what(file_path) is not 'jpeg':
            continue
        if debug:
            paths.append(file_path)
        else:
            # Throw gray space images, this takes long time if have many images
            # TODO: maybe can change to a fast way
            img = cv2.imread(file_path, cv2.IMREAD_UNCHANGED)
            if len(img.shape) == 3 and img.shape[2] != 1:
                paths.append(file_path)
    return paths
项目:pycustos    作者:fact-project    | 项目源码 | 文件源码
def send_image(self, chat_id, image):
        if isinstance(image, bytes):
            f = BytesIO(image)
            f.seek(0)
            extension = imghdr.what(f)
            self.bot.sendPhoto(chat_id, ('image.' + extension, f))

        elif isinstance(image, str):
            with open(image, 'rb') as f:
                self.bot.sendPhoto(chat_id, f)

        elif hasattr(image, 'read'):
            if hasattr(image, 'name'):
                self.bot.sendPhoto(chat_id, image)
            else:
                self.bot.sendPhoto(chat_id, ('image.png', image))

        else:
            raise TypeError(
                'image needs to be either a filename, bytes or file-like object'
            )
项目:supvisors    作者:julien6387    | 项目源码 | 文件源码
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()))
项目:hangoutsbot    作者:das7pad    | 项目源码 | 文件源码
def process_request(self, path, query_string, content):
        """default handler for incoming request
        path should contain a conversation id e.g. http://localhost/XXXXXXXXXXX/
        content is a valid json string with keys:
            echo                text string
            image
                base64encoded   base64-encoded image data
                filename        optional filename (else determined automatically via imghdr)
        """
        # parse incoming data
        payload = json.loads(content)

        path = path.split("/")
        conversation_id = path[1]
        if not conversation_id:
            logger.error("{}: conversation id must be provided as part of path".format(self.sinkname))
            return

        text = None
        if "echo" in payload:
            text = payload["echo"]

        image_data = None
        image_filename = None
        if "image" in payload:
            if "base64encoded" in payload["image"]:
                image_raw = base64.b64decode(payload["image"]["base64encoded"])
                image_data = io.BytesIO(image_raw)

            if "filename" in payload["image"]:
                image_filename = payload["image"]["filename"]
            else:
                image_type = imghdr.what('ignore', image_raw)
                image_filename = str(int(time.time())) + "." + image_type
                logger.info("automatic image filename: {}".format(image_filename))

        if not text and not image_data:
            logger.error("{}: nothing to send".format(self.sinkname))
            return

        await self.send_data(conversation_id, text, image_data=image_data, image_filename=image_filename)
项目:faceNet_RealTime    作者:jack55436001    | 项目源码 | 文件源码
def main(args):

    saveFace = None;
    cap = cv2.VideoCapture(0)
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        faces = face_cascade.detectMultiScale(frame, 1.3, 5)
        if len(faces) > 0:
            saveFace = frame
            break;
        # Display the resulting frame
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()
    cv2.imwrite('C:/Users/USER/Desktop/facenet-RealTime/src/face_data/saveFace.jpg',frame)

    mypath = 'C:/Users/USER/Desktop/facenet-RealTime/src/face_data'
    onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
    myImage = []
    for file in onlyfiles:
        isImage = None
        file = mypath + '/' + file
        isImage = imghdr.what(file)
        if isImage != None:
            myImage.append(file)

    #begin facenet
    cp.main(args,myImage);
项目:dminer    作者:infosecanon    | 项目源码 | 文件源码
def _load_image(captcha):
    if hasattr(captcha, 'read'):
        img = captcha.read()
    elif type(captcha) == bytearray:
        img = captcha
    else:
        img = ''
        try:
            captcha_file = open(captcha, 'rb')
        except Exception:
            raise
        else:
            img = captcha_file.read()
            captcha_file.close()
    if not len(img):
        raise ValueError('CAPTCHA image is empty')
    elif imghdr.what(None, img) is None:
        raise TypeError('Unknown CAPTCHA image type')
    else:
        return img
项目:som    作者:vsoch    | 项目源码 | 文件源码
def create_article(metadata):
    tmpdir = tempfile.mkdtemp()
    pmc_file = '%s/article.tar.gz' %(tmpdir)
    print('Downloading: %s' %(metadata['uid']))
    urllib.request.urlretrieve(metadata['download_url'], pmc_file)
    tar = tarfile.open(pmc_file, "r:gz")
    tar.extractall(tmpdir)
    files = glob('%s/%s/*' %(tmpdir,metadata['pmcid']))
    images = [x for x in files if imghdr.what(x) is not None]
    pdf_files = [x for x in files if x.lower().endswith('pdf')]        
    xml_file = [x for x in files if x.lower().endswith('xml')]
    images = images + pdf_files
    general_client.upload_dataset(images=images,
                                  texts=xml_file,
                                  collection=collection,
                                  uid=metadata['uid'],
                                  metadata=metadata)
    shutil.rmtree(tmpdir)


######################################################################
# Signals 
######################################################################
项目:histonets-cv    作者:sul-cidr    | 项目源码 | 文件源码
def __init__(self, content=None, image=None):
        self.image = None
        self.format = None
        if isinstance(image, Image):
            self.image = image.image
            self.format = image.format
        elif image is not None:
            self.image = image
        elif content:
            image_format = imghdr.what(file='', h=content)
            if image_format is not None:
                image_array = np.fromstring(content, np.uint8)
                self.image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
                self.format = image_format
        if self.image is None:
            raise click.BadParameter('Image format not supported')
项目:useful_script    作者:JyHu    | 项目源码 | 文件源码
def upload(img, need_zip):
    if os.path.exists(img) and os.path.isfile(img):
        if imghdr.what(img):
            if need_zip:
                try:
                    o_img = img + '.ori'
                    if not os.path.isfile(o_img) or not imghdr.what(o_img):     # ?????????????????
                        print('???? ?', img) 
                        s_img = tinify.from_file(img)
                        s_img.to_file(img + '.z')
                        os.rename(img, img + '.ori')
                        os.rename(img + '.z', img)
                except Exception as e:
                    print('??????')
            rstr = str(time.time())+''.join(random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 12))
            key = md5(rstr.encode('utf-8')).hexdigest()   # ??????????
            mime_type = 'image/%s' % img[img.rfind('.') + 1:]
            token = q.upload_token(bucket, key)
            ret, info = put_file(token, key, img, mime_type=mime_type, check_crc=True)
            if ret['key'] == key and ret['hash'] == etag(img): print('?????' + 'http://' + domain + '/' +key)
            else :t('????')
项目:useful_script    作者:JyHu    | 项目源码 | 文件源码
def classify_count(prj, res, et, ef):
    if os.path.isdir(prj):      # ??????????
        files = os.listdir(prj)
        for file in files:
            if file.find('.') == 0: continue    # ??????
            loc = file.rfind('.')               # ????????
            fname = file[:(loc if loc != -1 else len(file))]        # ???
            ftype = file[(loc + 1 if loc != -1 else len(file)):]    # ????
            curp = prj + '/' + file                                 # ?????????
            if fname in origin_folder or ftype in origin_type or ftype in et or fname in ef: continue   # ??????????
            if os.path.isdir(curp): classify_count(curp, res, et, ef)       # ???????????????
            elif imghdr.what(curp): continue        # ??????????????
            else:
                try:
                    with open(curp, 'r') as f:
                        words = re.sub('\\s+(/\\*([.\\s\\S]*?)\\*/)|(//.*)', '', f.read())          # ????????????????
                        codelines = [line for line in words.split('\n') if len(line.strip()) > 0]   # ???????????????????
                        if not ftype in res.keys(): res[ftype] = 0      # ????
                        res[ftype] += len(codelines)
                        if not file_count_key in res.keys() : res[file_count_key] = 1
                        res[file_count_key] += 1
                        print('%5d  %s' % (len(codelines), curp))
                except Exception as e: print(curp, e)
项目:deathbycaptcha    作者:hideki-saito    | 项目源码 | 文件源码
def _load_image(captcha):
    if hasattr(captcha, 'read'):
        img = captcha.read()
    elif type(captcha) == bytearray:
        img = captcha
    else:
        img = ''
        try:
            captcha_file = open(captcha, 'rb')
        except Exception:
            raise
        else:
            img = captcha_file.read()
            captcha_file.close()
    if not len(img):
        raise ValueError('CAPTCHA image is empty')
    elif imghdr.what(None, img) is None:
        raise TypeError('Unknown CAPTCHA image type')
    else:
        return img
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def _generate_image_filename(self, url_path, file):
        if callable(self._image_upload_to):
            raise Exception('Callable upload_to fields are not supported')

        root_path, extension = posixpath.splitext(url_path)
        if file:
            # Workaround: imghdr expects the files position on 0
            file.seek(0)
            extension = imghdr.what(file) or 'jpeg'

        basename = posixpath.basename(root_path)
        if not basename:
            basename = 'bplan'

        dirname = datetime.datetime.now().strftime(self._image_upload_to)
        filename = posixpath.join(dirname, basename + '.' + extension)

        return self._image_storage.get_available_name(filename)
项目:Saylua    作者:LikeMyBread    | 项目源码 | 文件源码
def image(base, items):
    items = items.split(',')

    # This will be replaced with calls to the database later
    base = os.path.join(app.static_folder, 'img/avatar/m.png')
    image_url_base = os.path.join(app.static_folder, 'img/avatar')
    item_images = os.listdir(image_url_base)

    result = Image.open(base, 'r')
    for i in items:
        if i.isdigit():
            i = int(i)
        if i >= 0 and i < len(item_images):
            image_url = os.path.join(image_url_base, item_images[i])
            if imghdr.what(image_url) == 'png':
                # Stack the image on top of the current result
                curr_image = Image.open(image_url, 'r')

                # Third parameter is a mask used to preserve alpha
                result.paste(curr_image, (0, 0), curr_image)

    return serve_pil_image(result)
项目:FavoriteGirls    作者:yulingtianxia    | 项目源码 | 文件源码
def download_proprocess_dataset():
    csvfile = open(GIRL_MARK_FILE, "r")
    reader = csv.reader(csvfile)
    train_data_arr = []
    test_data_arr = []
    for index, item in enumerate(reader):
        if index % 5 == 0:
            image_filename = download_girl_image(item[0], IMG_TEST_DIR)
            if imghdr.what(image_filename) is not None:
                img = process_image(image_filename)
                test_data_arr.append(mg.mark_girl(img, int(item[1])))
        else:
            image_filename = download_girl_image(item[0], IMG_TRAIN_DIR)
            if imghdr.what(image_filename) is not None:
                img = process_image(image_filename)
                train_data_arr.append(mg.mark_girl(img, int(item[1])))
    writer = tf.python_io.TFRecordWriter(mg.FILE_NAME_TEST)
    for data in test_data_arr:
        writer.write(data)
    writer.close()
    writer = tf.python_io.TFRecordWriter(mg.FILE_NAME_TRAIN)
    for data in train_data_arr:
        writer.write(data)
    writer.close()
项目:mediafile    作者:beetbox    | 项目源码 | 文件源码
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)
项目:book    作者:zhaiyifei    | 项目源码 | 文件源码
def replace_img():
    '''??????????????'''
    #???????
    base_path = os.getcwd().split('ESBook')[0]
    file_path = r'ESBook\data\img'
    fengmian_path = r'ESBook\data\img_fengmian\fengmian.gif'
    img_file = ''.join([base_path,file_path])
    #print img_file
    #??????
    fengmiam_img = ''.join([base_path,fengmian_path])
    img_name_list = os.listdir(img_file)
    #print img_name_list
    for img_name in img_name_list:
        #???????????
        img_path = os.path.join(img_file,img_name)
        #?????????????????
        if not imghdr.what(img_path):
            print img_path
            #?????????????????????
            shutil.copyfile(fengmiam_img,img_path)

#replace_img()
项目:Flickr3    作者:chew-z    | 项目源码 | 文件源码
def valid_img(f):
    """
    Is this a valid image that we can use to upload?

    :param f: str that indicates the file directory.
    :return: boolean
    """
    if not os.path.isfile(f) :
        return False
    if re.search(r'\.(jpg|gif|png|tiff|mp4|mp2|avi|wmv|mov|m4v)$', f, flags=re.IGNORECASE):
        return True
    try:
        file_type = imghdr.what(f)
        supported_types = ['jpeg', 'gif', 'png']
        if file_type in supported_types:
            return True
    except AttributeError as e:
        # You probably passed something that is not a path.
        logging.warning(e)
    except IOError as e:
        # You passed a path that does not exist, or you do not have access to it.
        logging.warning(e)
    return False
项目:fc-python-sdk    作者:aliyun    | 项目源码 | 文件源码
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)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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)
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def validate_image(value):
    """
    Validates if the image which is uploading is exactly image, because file can be renamed.
    Raises an error if validation not passed.

    :param str value: The file object.
    """
    if not imghdr.what(value):
        raise ValidationError('Tried to upload not an image!')


# ----------------------------------------------------------------------------------------------------------------------
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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)
项目:document_clipper    作者:reclamador    | 项目源码 | 文件源码
def merge(self, final_pdf_path, actions, append_blank_page=False):
        """
        Merge files (images and pdfs) in to one PDF
        :param final_pdf_path: file path to save pdf
        :param actions: list of tuples, each tuple consisting of a PDF file path, and the amount of clockwise rotation
        to apply to the document.
        :param append_blank_page: append a blank page between documents if True.
        :return:
        """
        real_actions = []
        tmp_to_delete_paths = []
        for file_path, rotation in actions:
            if imghdr.what(file_path):
                img = Image.open(file_path)
                path = self.image_to_pdf(img)
                action = (path, rotation)
                real_actions.append(action)
                tmp_to_delete_paths.append(path)
            else:
                action = (file_path, rotation)
                real_actions.append(action)

        self.merge_pdfs(final_pdf_path, real_actions, append_blank_page)

        for path_to_delete in tmp_to_delete_paths:
            os.remove(path_to_delete)
项目:mobot    作者:JokerQyou    | 项目源码 | 文件源码
def is_image(stream):
        """Check if the content file is an image by analyzing its headers.

        Args:
            stream (str): A str representing the content of a file.

        Returns:
            str: The str mimetype of an image.
        """
        image = imghdr.what(None, stream)
        if image:
            return 'image/%s' % image

        raise TelegramError('Could not parse file content')
项目:zoocore    作者:dsparrow27    | 项目源码 | 文件源码
def isImage(path):
    return imghdr.what(path) is not None
项目:zoocore    作者:dsparrow27    | 项目源码 | 文件源码
def imageSupportByQt(path):
    imageType = imghdr.what(path)
    if imageType is not None:
        return imageType.lower() in QTSUPPORTEDIMAGES
    return False
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def adjust_content_type(content_type, body=None, filename=None):
    """Adjust content type based on filename or body contents
    """
    if filename and str(content_type) == 'application/octet-stream':
        # check if our internal guess returns anything
        guessed = _guess_type(filename)
        if guessed:
            return guessed

        # our internal attempt didn't return anything, use mimetypes
        guessed = mimetypes.guess_type(filename)[0]
        if guessed:
            main, sub = fix_content_type(
                guessed, default=('application', 'octet-stream'))
            content_type = ContentType(main, sub)

    if content_type.main == 'image' and body:
        sub = imghdr.what(None, body)
        if sub:
            content_type = ContentType('image', sub)

    elif content_type.main == 'audio' and body:
        sub = audio._whatsnd(body)
        if sub:
            content_type = ContentType('audio', sub)

    return content_type
项目:ConditionalGAN    作者:seungjooli    | 项目源码 | 文件源码
def is_image_valid(filepath):
    return imghdr.what(filepath) is not None
项目:notebooks    作者:fluentpython    | 项目源码 | 文件源码
def picture_type(octets):
    pict_type = imghdr.what(None, octets)
    if pict_type is None:
        if (octets.startswith(b'<') and
                b'<svg' in octets[:200] and
                octets.rstrip().endswith(b'</svg>')):
            pict_type = 'svg'
    return pict_type
项目:django-imperavi-widget    作者:dzaytsev91    | 项目源码 | 文件源码
def uploaded_images_json(request, upload_path=None):
    upload_path = upload_path or UPLOAD_PATH
    results = list()
    path = os.path.join(settings.MEDIA_ROOT, upload_path)
    if os.path.isdir(path):
        for image in os.listdir(path):
            image_path = '{0}{1}'.format(path, smart_str(image))
            if not os.path.isdir(image_path) and imghdr.what(image_path):
                thumb = get_thumbnail(image_path, '100x74', crop='center')
                image_url = os.path.join(settings.MEDIA_URL, upload_path, image)
                results.append({'thumb': thumb.url, 'image': image_url})
        return HttpResponse(json.dumps(results))
    return HttpResponse('{}')
项目:cat-that    作者:mcrowson    | 项目源码 | 文件源码
def valid_image_file_odl(file_obj):
    res = imghdr.what('ignored.txt', h=file_obj.read())
    return res in ALLOWED_EXTENSIONS
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
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)
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
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)
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
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)
项目:pytrip    作者:pytrip    | 项目源码 | 文件源码
def test_generate(self):
        fd, outfile = tempfile.mkstemp(suffix='.png')

        # convert CT cube to DICOM
        pytrip.utils.rst_plot.main([self.rst_file, outfile])

        # check if destination file is not empty
        self.assertTrue(os.path.exists(outfile))
        self.assertGreater(os.path.getsize(outfile), 0)
        self.assertEqual(imghdr.what(outfile), 'png')

        os.close(fd)  # Windows needs it
        os.remove(outfile)  # we need only temp filename, not the file
项目:pytrip    作者:pytrip    | 项目源码 | 文件源码
def test_relative_dos_plot(self):
        working_dir = tempfile.mkdtemp()  # make temp working dir for output file
        output_file = os.path.join(working_dir, "foo.png")

        pytrip.utils.dvhplot.main(args=[self.dos, self.vdx, 'target', '-l', '-v', '-o', output_file])

        logger.info("Checking if " + output_file + " is PNG")
        self.assertEqual(imghdr.what(output_file), 'png')

        logger.info("Removing " + working_dir)
        shutil.rmtree(working_dir)
项目:pytrip    作者:pytrip    | 项目源码 | 文件源码
def test_absolute_dos_plot(self):
        working_dir = tempfile.mkdtemp()  # make temp working dir for output file
        output_file = os.path.join(working_dir, "foo.png")

        pytrip.utils.dvhplot.main(args=[self.dos, self.vdx, 'target', '-l', '-v', '-d 2.0', '-o', output_file])

        logger.info("Checking if " + output_file + " is PNG")
        self.assertEqual(imghdr.what(output_file), 'png')

        logger.info("Removing " + working_dir)
        shutil.rmtree(working_dir)
项目:pytrip    作者:pytrip    | 项目源码 | 文件源码
def test_let_plot(self):
        working_dir = tempfile.mkdtemp()  # make temp working dir for output file
        output_file = os.path.join(working_dir, "foo.png")

        pytrip.utils.dvhplot.main(args=[self.let, self.vdx, 'target', '-l', '-v', '-o', output_file])

        logger.info("Checking if " + output_file + " is PNG")
        self.assertEqual(imghdr.what(output_file), 'png')

        logger.info("Removing " + working_dir)
        shutil.rmtree(working_dir)
项目:pytrip    作者:pytrip    | 项目源码 | 文件源码
def test_convert_all(self):
        working_dir = tempfile.mkdtemp()  # make temp working dir for converter output files

        pytrip.utils.cubeslice.main(args=['--data', self.dos, '--ct', self.ctx, '-o', working_dir])
        output_file_list = glob.glob(os.path.join(working_dir, "*.png"))

        logger.info("Checking if number of output files is sufficient")
        self.assertEqual(len(output_file_list), 300)

        for output_file in output_file_list:
            logger.info("Checking if " + output_file + " is PNG")
            self.assertEqual(imghdr.what(output_file), 'png')

        logger.info("Removing " + working_dir)
        shutil.rmtree(working_dir)
项目:ig_upload_bot    作者:skawm    | 项目源码 | 文件源码
def getImageSize(fname):
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            raise RuntimeError("Invalid Header")
        if imghdr.what(fname) == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                raise RuntimeError("PNG: Invalid check")
            width, height = struct.unpack('>ii', head[16:24])
        elif imghdr.what(fname) == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif imghdr.what(fname) == 'jpeg':
            fhandle.seek(0) # Read 0xff next
            size = 2
            ftype = 0
            while not 0xc0 <= ftype <= 0xcf:
                fhandle.seek(size, 1)
                byte = fhandle.read(1)
                while ord(byte) == 0xff:
                    byte = fhandle.read(1)
                ftype = ord(byte)
                size = struct.unpack('>H', fhandle.read(2))[0] - 2
            # We are at a SOFn block
            fhandle.seek(1, 1)  # Skip `precision' byte.
            height, width = struct.unpack('>HH', fhandle.read(4))
        else:
            raise RuntimeError("Unsupported format")
        return width, height
项目:ig_upload_bot    作者:skawm    | 项目源码 | 文件源码
def getImageSize(fname):
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            raise RuntimeError("Invalid Header")
        if imghdr.what(fname) == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                raise RuntimeError("PNG: Invalid check")
            width, height = struct.unpack('>ii', head[16:24])
        elif imghdr.what(fname) == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif imghdr.what(fname) == 'jpeg':
            fhandle.seek(0) # Read 0xff next
            size = 2
            ftype = 0
            while not 0xc0 <= ftype <= 0xcf:
                fhandle.seek(size, 1)
                byte = fhandle.read(1)
                while ord(byte) == 0xff:
                    byte = fhandle.read(1)
                ftype = ord(byte)
                size = struct.unpack('>H', fhandle.read(2))[0] - 2
            # We are at a SOFn block
            fhandle.seek(1, 1)  # Skip `precision' byte.
            height, width = struct.unpack('>HH', fhandle.read(4))
        else:
            raise RuntimeError("Unsupported format")
        return width, height
项目:hangoutsbot    作者:das7pad    | 项目源码 | 文件源码
def process_request(self, path, query_string, content):
        payload = json.loads(content)

        path = path.split("/")
        conversation_id = path[1]
        if not conversation_id:
            raise ValueError("conversation id must be provided in path")

        text = None
        if "echo" in payload:
            text = payload["echo"]

        image_data = None
        image_filename = None
        if "image" in payload:
            if "base64encoded" in payload["image"]:
                image_raw = base64.b64decode(payload["image"]["base64encoded"])
                image_data = io.BytesIO(image_raw)

            if "filename" in payload["image"]:
                image_filename = payload["image"]["filename"]
            else:
                image_type = imghdr.what('ignore', image_raw)
                image_filename = str(int(time.time())) + "." + image_type
                logger.info("automatic image filename: {}".format(image_filename))

        if not text and not image_data:
            raise ValueError("nothing to send")

        results = await self.send_data(conversation_id, text, image_data=image_data, image_filename=image_filename)

        return results
项目:hangoutsbot    作者:das7pad    | 项目源码 | 文件源码
def process_payload(self, path, query_string, payload):
        logging.warning("[DEPRECATED] simpledemo.webhookReceiver, use sinks.generic.SimpleMessagePoster")

        sinkname = self.sinkname

        path = path.split("/")
        conversation_id = path[1]
        if conversation_id is None:
            print("{}: conversation id must be provided as part of path".format(sinkname))
            return

        image_id = None
        if "image" in payload:
            image_data = False
            image_filename = False
            image_type = 'unknown'
            if "base64encoded" in payload["image"]:
                raw = base64.b64decode(payload["image"]["base64encoded"], None, True)
                image_data = io.BytesIO(raw)
                image_type = imghdr.what('ignore', raw)
                if not image_type:
                  image_type = 'error'
            if "filename" in payload["image"]:
                image_filename = payload["image"]["filename"]
            else:
                image_filename = str(int(time.time())) + "." + image_type
            print("{}: uploading image: {}".format(sinkname, image_filename))
            image_id = await webhookReceiver._bot._client.upload_image(image_data, filename=image_filename)

        html = ""
        if "echo" in payload:
            html = payload["echo"]
        else:
            # placeholder text
            html = "<b>hello world</b>"
        segments = simple_parse_to_segments(html)
        print("{} sending segments: {}".format(sinkname, len(segments)))

        await self._bot.coro_send_message(conversation_id, segments, context=None, image_id=image_id)
项目:InstagramPi    作者:sabas1080    | 项目源码 | 文件源码
def getImageSize(fname):
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            raise RuntimeError("Invalid Header")
        if imghdr.what(fname) == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                raise RuntimeError("PNG: Invalid check")
            width, height = struct.unpack('>ii', head[16:24])
        elif imghdr.what(fname) == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif imghdr.what(fname) == 'jpeg':
            fhandle.seek(0) # Read 0xff next
            size = 2
            ftype = 0
            while not 0xc0 <= ftype <= 0xcf:
                fhandle.seek(size, 1)
                byte = fhandle.read(1)
                while ord(byte) == 0xff:
                    byte = fhandle.read(1)
                ftype = ord(byte)
                size = struct.unpack('>H', fhandle.read(2))[0] - 2
            # We are at a SOFn block
            fhandle.seek(1, 1)  # Skip `precision' byte.
            height, width = struct.unpack('>HH', fhandle.read(4))
        else:
            raise RuntimeError("Unsupported format")
        return width, height
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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)
项目:flask-online-store    作者:sunhuachuang    | 项目源码 | 文件源码
def __call__(self, form, field):
        if field.data is None or imghdr.what('unused', field.data.read()) is None:
            message = self.message or 'An image file is required'
            raise StopValidation(message)

        field.data.seek(0)
项目:e2m3u2bouquet    作者:su1s    | 项目源码 | 文件源码
def picon_post_processing(self, piconfilepath):
        """Check type of image received and convert to png
        if necessary
        """
        ext = ""
        # get image type
        try:
            ext = imghdr.what(piconfilepath)
        except Exception, e:
            if DEBUG:
                print(e)
            return
        # if image but not png convert to png
        if (ext is not None) and (ext is not 'png'):
            if DEBUG:
                print('Converting Picon to png')
            try:
                Image.open(piconfilepath).save("{}.{}".format(piconfilepath, 'png'))
            except Exception, e:
                if DEBUG:
                    print(e)
                return
            try:
                # remove non png file
                os.remove(piconfilepath)
            except Exception, e:
                if DEBUG:
                    print(e)
                return
        else:
            # rename to correct extension
            try:
                os.rename(piconfilepath, "{}.{}".format(piconfilepath, ext))
            except Exception, e:
                if DEBUG:
                    print(e)
            pass
项目:mkepub    作者:anqxyr    | 项目源码 | 文件源码
def set_cover(self, data):
        """Set the cover image to the given data."""
        self._cover = 'cover.' + imghdr.what(None, h=data)
        with open(str(self.path / 'EPUB/covers' / self._cover), 'wb') as file:
            file.write(data)
        self._write('cover.xhtml', 'EPUB/cover.xhtml', cover=self._cover)