예제 #1
0
파일: preview.py 프로젝트: BoPeng/SOS
def preview_pdf(filename):
    try:
        # this import will fail even if wand is installed
        # if imagemagick is not installed properly.
        from wand.image import Image

        img = Image(filename=filename)
        return {
            "text/html": HTML('<iframe src={0} width="100%"></iframe>'.format(filename)).data,
            "image/png": base64.b64encode(img._repr_png_()).decode("ascii"),
        }
    except Exception as e:
        env.logger.error(e)
        return {"text/html": HTML('<iframe src={0} width="100%"></iframe>'.format(filename)).data}
예제 #2
0
파일: preview.py 프로젝트: BoPeng/SOS
def preview_img(filename):
    with open(filename, "rb") as f:
        image = f.read()

    import imghdr

    image_type = imghdr.what(None, image)
    image_data = base64.b64encode(image).decode("ascii")
    if image_type != "png":
        try:
            from wand.image import Image

            img = Image(filename=filename)
            return {"image/" + image_type: image_data, "image/png": base64.b64encode(img._repr_png_()).decode("ascii")}
        except Exception:
            return {"image/" + image_type: image_data}
    else:
        return {"image/" + image_type: image_data}
예제 #3
0
def preview_img(filename, kernel=None, style=None):
    with open(filename, 'rb') as f:
        image = f.read()

    import imghdr
    image_type = imghdr.what(None, image)
    image_data = base64.b64encode(image).decode('ascii')
    if image_type != 'png':
        try:
            from wand.image import Image
            img = Image(filename=filename)
            return {
                'image/' + image_type: image_data,
                'image/png': base64.b64encode(img._repr_png_()).decode('ascii')
            }
        except Exception:
            return {'image/' + image_type: image_data}
    else:
        return {'image/' + image_type: image_data}
예제 #4
0
파일: preview.py 프로젝트: mr-c/SOS
def preview_pdf(filename):
    try:
        # this import will fail even if wand is installed
        # if imagemagick is not installed properly.
        from wand.image import Image
        img = Image(filename=filename)
        return {
            'text/html':
            HTML('<iframe src={0} width="100%"></iframe>'.format(
                filename)).data,
            'image/png':
            base64.b64encode(img._repr_png_()).decode('ascii')
        }
    except Exception as e:
        env.logger.error(e)
        return {
            'text/html':
            HTML(
                '<iframe src={0} width="100%"></iframe>'.format(filename)).data
        }
예제 #5
0
파일: preview.py 프로젝트: pgcudahy/sos
def preview_img(filename, kernel=None, style=None):
    with open(filename, "rb") as f:
        image = f.read()
    import imghdr

    image_type = imghdr.what(None, image)
    image_data = base64.b64encode(image).decode("ascii")

    args = None
    meta = {}
    if style is not None and "options" in style:
        parser = _preview_img_parser()
        try:
            args = parser.parse_args(style["options"])
            meta.update({
                "image/png":
                dict(([["width", args.width]] if args.width else []) +
                     ([["height", args.height]] if args.height else []))
            })
        except SystemExit:
            return

    if image_type != "png":
        try:
            if image_type == "gif":
                return {"image/png": image_data}, meta
            else:
                from wand.image import Image

                img = Image(filename=filename)
                return {
                    "image/" + image_type:
                    image_data,
                    "image/png":
                    base64.b64encode(img._repr_png_()).decode("ascii"),
                }, meta
        except Exception:
            return {"image/" + image_type: image_data}, meta
    else:
        return {"image/" + image_type: image_data}, meta
예제 #6
0
def preview_img(filename, kernel=None, style=None):
    with open(filename, 'rb') as f:
        image = f.read()
    import imghdr
    image_type = imghdr.what(None, image)
    image_data = base64.b64encode(image).decode('ascii')

    args = None
    meta = {}
    if style is not None and 'options' in style:
        parser = _preview_img_parser()
        try:
            args = parser.parse_args(style['options'])
            meta.update({
                'image/png':
                    dict(([['width', args.width]] if args.width else []) +
                         ([['height', args.height]] if args.height else []))
            })
        except SystemExit:
            return

    if image_type != 'png':
        try:
            if image_type == 'gif':
                return {'image/png': image_data}, meta
            else:
                from wand.image import Image
                img = Image(filename=filename)
                return {
                    'image/' + image_type:
                        image_data,
                    'image/png':
                        base64.b64encode(img._repr_png_()).decode('ascii')
                }, meta
        except Exception:
            return {'image/' + image_type: image_data}, meta
    else:
        return {'image/' + image_type: image_data}, meta
예제 #7
0
def preview_pdf(filename, kernel=None, style=None):
    use_png = False
    if style is not None and 'style' in style:
        if style['style'] != 'png':
            if kernel is not None and style['style'] is not None:
                kernel.warn(
                    f'Option --style of PDF preview only accept parameter png: {style["style"]} provided'
                )
        else:
            use_png = True
    if use_png:
        try:
            # this import will fail even if wand is installed
            # if imagemagick is not installed properly.
            from wand.image import Image
            img = Image(filename=filename)
            nPages = len(img.sequence)
            pages = list(range(nPages))

            if style is not None and 'options' in style:
                parser = _preview_pdf_parser()
                try:
                    args = parser.parse_args(style['options'])
                except SystemExit:
                    return
                if args.pages is not None:
                    pages = [x - 1 for x in args.pages]
                    for p in pages:
                        if p >= nPages:
                            if kernel is not None:
                                kernel.warn(
                                    f'Page {p} out of range of the pdf file ({nPages} pages)'
                                )
                            pages = list(range(nPages))
                            break
            # single page PDF
            if len(pages) == 1 and pages[0] == 0:
                return {
                    'image/png':
                    base64.b64encode(img._repr_png_()).decode('ascii')
                }
            elif len(pages) == 1:
                # if only one page
                return {
                    'image/png':
                    base64.b64encode(
                        Image(img.sequence[pages[0]])._repr_png_()).decode(
                            'ascii')
                }
            else:
                image = Image(width=img.width, height=img.height * len(pages))
                for i, p in enumerate(pages):
                    image.composite(img.sequence[p],
                                    top=img.height * i,
                                    left=0)
                return {
                    'image/png':
                    base64.b64encode(image._repr_png_()).decode('ascii')
                }
        except Exception as e:
            if kernel is not None:
                kernel.warn(e)
            return {
                'text/html':
                HTML(f'<iframe src={filename} width="100%"></iframe>').data
            }
    else:
        # by default use iframe, because PDF figure can have multiple pages (#693)
        # try to get width and height
        try:
            from wand.image import Image
            img = Image(filename=filename)
            return {
                'text/html':
                HTML(
                    f'<iframe src={filename} width="800px" height="{img.height/img.width * 800}px"></iframe>'
                ).data
            }
        except Exception as e:
            kernel.warn(e)
            return {
                'text/html':
                HTML(f'<iframe src={filename} width="100%"></iframe>').data
            }
예제 #8
0
파일: preview.py 프로젝트: pgcudahy/sos
def preview_pdf(filename, kernel=None, style=None):
    use_png = False
    warn = kernel.warn if kernel is not None else env.logger.warning
    if style is not None and "style" in style:
        if style["style"] != "png":
            if style["style"] is not None:
                warn(
                    f'Option --style of PDF preview only accept parameter png: {style["style"]} provided'
                )
        else:
            use_png = True
    args = None
    if style is not None and "options" in style:
        parser = _preview_pdf_parser()
        try:
            args = parser.parse_args(style["options"])
        except SystemExit:
            return
    meta = {}
    embed_options = ""
    if args and (args.width or args.height):
        meta.update({
            "image/png":
            dict(([["width", args.width]] if args.width else []) +
                 ([["height", args.height]] if args.height else []))
        })
        embed_options += (f'width="{args.width}" ' if args.width else " ") + (
            f'height="{args.height}" ' if args.height else " ")
    if use_png:
        try:
            # this import will fail even if wand is installed
            # if imagemagick is not installed properly.
            from wand.image import Image

            img = Image(filename=filename, resolution=args.dpi)

            if img.width == 0 or img.height == 0:
                raise ValueError("Image appears to have zero width or height")
            nPages = len(img.sequence)
            pages = list(range(nPages))

            if args and args.pages is not None:
                pages = [x - 1 for x in args.pages]
                for p in pages:
                    if p >= nPages:
                        warn(
                            f"Page {p} out of range of the pdf file ({nPages} pages)"
                        )
                        pages = list(range(nPages))
                        break
            # single page PDF
            if len(pages) == 1 and pages[0] == 0:
                return {
                    "image/png":
                    base64.b64encode(img._repr_png_()).decode("ascii")
                }, meta
            elif len(pages) == 1:
                # if only one page
                return {
                    "image/png":
                    base64.b64encode(
                        Image(img.sequence[pages[0]])._repr_png_()).decode(
                            "ascii")
                }, meta
            else:
                widths = [img.sequence[p].width for p in pages]
                heights = [img.sequence[p].height for p in pages]
                image = Image(width=max(widths), height=sum(heights))
                for i, p in enumerate(pages):
                    image.composite(img.sequence[p],
                                    top=sum(heights[:i]),
                                    left=0)
                image.format = "png"
                with io.BytesIO() as out:
                    image.save(file=out)
                    img_data = out.getvalue()
                return {
                    "image/png": base64.b64encode(img_data).decode("ascii")
                }, meta
        except Exception as e:
            warn(e)
            return {
                "text/html":
                f'<embed src="{filename}" {embed_options} type="application/pdf" />'
            }
    else:
        # by default use iframe, because PDF figure can have multiple pages (#693)
        return {
            "text/html":
            f'<embed src="{filename}" {embed_options} type="application/pdf" />'
        }