Ejemplo n.º 1
0
def send_file_helper(context, chat_id, filename, file_content, caption):
    """
    Helper for handle generic files.
    If the file is a pdf, it will be converted and send as image/s.
    If the file is already an image it will not be processed.
    If the file is any other type, it will be send as document.
    """

    mime = filetype.guess_mime(file_content)
    if mime == 'application/pdf':
        pages = convert_from_bytes(file_content, 500)
        images = []
        for page in pages:
            file = io.BytesIO()
            page.save(file, 'png')
            file.name = filename
            file.seek(0)
            images.append(file)
        send_images_helper(context, chat_id, images, caption, '')

    elif filetype.image(file_content) is not None:
        send_images_helper(context, chat_id, [io.BytesIO(file_content)],
                           caption, '')

    else:
        content = io.BytesIO(file_content)
        context.bot.send_document(chat_id=chat_id,
                                  document=content,
                                  filename=filename,
                                  parse_mode=ParseMode.MARKDOWN,
                                  caption=caption)
Ejemplo n.º 2
0
def is_valid_image_file(parser, filename):
    """Simple check the filename is an image file"""

    if not os.path.isfile(filename):
        parser.error(f'The file {filename} does not exist!')
    if not filetype.image(filename):
        parser.error(f'The file {filename} not an image file!')
    return filename
Ejemplo n.º 3
0
def assertFileType(content_type=None, name=None):
    if content_type == "application/zip" or content_type == "application/x-zip-compressed":
        return "zip", ".zip"
    elif content_type and content_type.find("image") == 0:
        return "img", get_type_obj(content_type, getExtName(name)).extension
    else:
        try:
            if filetype.guess_mime(name) == "application/zip":
                return "zip", ".zip"
            elif filetype.image(name):
                return "img", get_type_obj(content_type,
                                           getExtName(name)).extension
        except FileNotFoundError:
            pass
        raise RequestHandleFailException(415, "输入的文件不是支持的图片或zip类型!")
Ejemplo n.º 4
0
def unzipAllChooseImages(zipPath):
    exts = os.path.splitext(zipPath)
    foldername = exts[0]
    if len(exts) < 2 or exts[1] != ".zip":
        os.rename(zipPath, foldername + ".zip")
        zipPath = foldername + ".zip"
    with zipfile.ZipFile(zipPath, 'r') as zipf:
        zipf.extractall(path=foldername)
    res = []
    for root, dirs, files in os.walk(foldername):
        for file in files:
            realPath = os.path.join(root, file)
            kind = filetype.image(realPath)
            if kind:
                res.append(realPath)
    if len(res) <= 0:
        os.remove(zipPath)
        os.remove(foldername)
        raise RequestHandleFailException(415, "上传的压缩包中不含有任何的图片类型文件,因此无法处理")
    return res, foldername
Ejemplo n.º 5
0
    def get_file_type(self):
        """Determine type of file.

        Check extension before bytes, to correctly identify documents
        and PDF files. All other types are detected by bytes.
        """
        extension = splitext(self.component_file.name)[1][1:]
        for type_code, type_data in self.COMPONENT_TYPE_DATA.items():
            if extension in type_data.get('extensions', set()):
                return type_code

        file_obj = self.component_file.open()
        if filetype.image(file_obj):
            return self.TYPE_IMAGE
        elif filetype.video(file_obj):
            return self.TYPE_VIDEO
        elif filetype.audio(file_obj):
            return self.TYPE_AUDIO
        elif filetype.archive(file_obj):
            return self.TYPE_ARCHIVE
        else:
            return self.TYPE_OTHER
Ejemplo n.º 6
0
import filetype

filename = "/path/to/file.jpg"

if filetype.image(filename):
    print(f"{filename} is a valid image...")
elif filetype.video(filename):
    print(f"{filename} is a valid video...")
else:
    print("not image file")
Ejemplo n.º 7
0
 def wx_file_type(self, path):
     if filetype.image(str(path)) is not None:
         return 'img'
     if filetype.video(str(path)) is not None:
         return 'vid'
     return 'fil'
Ejemplo n.º 8
0
def get_image_info(fp):
    """Reads some image info from a file descriptor."""
    head = fp.read(32)
    fp.seek(0)
    if len(head) < 24:
        return 'unknown', None, None

    magic_bytes = b'<?xml', b'<svg'
    if any(map(head.strip().startswith, magic_bytes)):
        return get_svg_info(fp)

    _type = filetype.image(bytearray(head))
    fmt = _type.mime.split("/")[1] if _type else None

    width = None
    height = None
    if fmt == 'png':
        check = struct.unpack('>i', head[4:8])[0]
        if check == 0x0d0a1a0a:
            width, height = struct.unpack('>ii', head[16:24])
    elif fmt == 'gif':
        width, height = struct.unpack('<HH', head[6:10])
    elif fmt == 'jpeg':
        # specification available under
        # http://www.w3.org/Graphics/JPEG/itu-t81.pdf
        # Annex B (page 31/35)

        # we are looking for a SOF marker ("start of frame").
        # skip over the "start of image" marker
        # (filetype detection took care of that).
        fp.seek(2)

        while True:
            byte = fp.read(1)

            # "All markers are assigned two-byte codes: an X’FF’ byte
            # followed by a byte which is not equal to 0 or X’FF’."
            if not byte or ord(byte) != 0xff:
                raise Exception("Malformed JPEG image.")

            # "Any marker may optionally be preceded by any number
            # of fill bytes, which are bytes assigned code X’FF’."
            while ord(byte) == 0xff:
                byte = fp.read(1)

            if ord(byte) not in _JPEG_SOF_MARKERS:
                # header length parameter takes 2 bytes for all markers
                length = struct.unpack('>H', fp.read(2))[0]
                fp.seek(length - 2, 1)
                continue

            # else...
            # see Figure B.3 – Frame header syntax (page 35/39) and
            # Table B.2 – Frame header parameter sizes and values
            # (page 36/40)
            fp.seek(3, 1)  # skip header length and precision parameters
            height, width = struct.unpack('>HH', fp.read(4))

            if height == 0:
                # "Value 0 indicates that the number of lines shall be
                # defined by the DNL marker [...]"
                #
                # DNL is not supported by most applications,
                # so we won't support it either.
                raise Exception("JPEG with DNL not supported.")

            break

        # if the file is rotated, we want, for all intents and purposes,
        # to return the dimensions swapped. (all client apps will display
        # the image rotated, and any template computations are likely to want
        # to make decisions based on the "visual", not the "real" dimensions.
        # thumbnail code also depends on this behaviour.)
        fp.seek(0)
        if is_rotated(fp):
            width, height = height, width
    else:
        fmt = None

    return fmt, width, height