예제 #1
0
def convert_pdf_to_img(blob, img_type="jpg", quality=75, resolution=200):
    """
    Converts PDF with multiple pages into one image.
    It needs the file content NOT the filename or ioBytes and returns the image content.
    Note: It has memory leak!!
    http://stackoverflow.com/a/26233785/1497443

    Example:

    with open('my.pdf', "r") as f:
        file_content = f.read()

    # import ipdb
    # ipdb.set_trace()
    hh = convert_pdf_to_jpg(file_content)

    with open('my.jpg', 'wb') as f:
        f.write(hh)
    """
    from wand.image import Image as WandImage
    from wand.color import Color as WandColor

    pdf = WandImage(blob=blob, resolution=resolution)

    pages = len(pdf.sequence)

    wimage = WandImage(width=pdf.width, height=pdf.height * pages, background=WandColor("white"))

    for i in xrange(pages):
        wimage.composite(pdf.sequence[i], top=pdf.height * i, left=0)

    if img_type == "jpg":
        wimage.compression_quality = quality

    return wimage.make_blob(img_type)
예제 #2
0
def createAndStoreThumbnail(**kwargs):

    # fileDirectory = "/home/akshat/Desktop/"
    # inFileName="test_doc_2.pdf"
    # outFileName="myOutputfile.jpg"
    imageFromPdf = Image(filename=kwargs["fileLocation"] + kwargs["fileName"])
    # pages = len(imageFromPdf.sequence)
    # print(pages)

    # creates an empty Image.
    image = Image(width=imageFromPdf.width, height=imageFromPdf.height)

    # resize the empty image
    image.sample(470, 330)

    #superimpose on the empty image the argument given, at the position specified
    image.composite(imageFromPdf.sequence[0], top=0, left=0)
    image.background_color = Color("white")
    image.alpha_channel = 'remove'
    # for i in range(pages):
    # 	image.composite(
    #  		imageFromPdf.sequence[i],
    #  		top=imageFromPdf.height * i,
    #  		left=0
    # 	)

    image.format = "jpg"
    image.save(filename=kwargs["imageLocation"] + kwargs["imageName"] + ".jpg")
    return kwargs["imageName"] + ".jpg"
    # display(image)
예제 #3
0
def pdf_to_text(filename):
    pdf = IM(filename=filename, resolution=300)
    pages = len(pdf.sequence)
    image = IM(width=pdf.width, height=pdf.height * pages)

    for i in xrange(pages):
        image.composite(
            pdf.sequence[i],
            top=pdf.height * i,
            left=0
        )
    img = image.convert('png')

    with tempfile.NamedTemporaryFile(prefix="tess_") as temp_file:
        img.save(filename=temp_file.name)

        try:
            temp = tempfile.NamedTemporaryFile(delete=False)
            process = subprocess.Popen(['tesseract', temp_file.name, temp.name], \
                                       stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            process.communicate()

            with open(temp.name + '.txt', 'r') as handle:
                contents = handle.read()
                os.remove(temp.name + '.txt')
                os.remove(temp.name)
                print contents
        except:
            print "ERROR"
예제 #4
0
class UVcard:

    WIDTH = 1024
    HEIGHT = 1024

    BACKGROUND_PATH = os.path.join(os.path.dirname(__file__), 'static',
                                   'images', 'default_uvcard.jpg')

    def __init__(self, *parts, **kwargs):
        """
        :type parts: list[UVcardPart]
        """

        self._background_image = Image(filename=self.BACKGROUND_PATH)
        self._width = kwargs.get('width', self.WIDTH)
        self._height = kwargs.get('height', self.HEIGHT)
        self._parts = parts

        self._composite()

    def _composite(self):
        for part in self._parts:
            if not isinstance(part, UVcardPart):
                raise ValueError(
                    'Image part should be instance of <class "UVcardPath">')
            self._background_image.composite(part.image, *part.position)

    def make_blob(self):
        return self._background_image.make_blob('jpeg')
예제 #5
0
def create_matches(catcierge_json, output_file):

    match_count = catcierge_json["match_count"]
    match_imgs = []
    total_width = 0
    total_height = 0
    i = 1

    for match in catcierge_json["matches"][:match_count]:

        step_count = match["step_count"]
        img_paths = []

        for step in match["steps"][:step_count]:
            img_paths.append(step["path"])

        img = compose_adaptive_prey(img_paths=img_paths,
                                    gap=5,
                                    description=match["description"],
                                    caption="Match %d" % i)

        total_width += img.width
        total_height = max(total_height, img.height)
        match_imgs.append(img)
        i += 1

    fimg = Image(width=total_width, height=total_height)

    x = 0
    for img in match_imgs:
        fimg.composite(img, left=x, top=0)
        x += img.width

    return fimg
예제 #6
0
def convert_pdf_to_png(from_file, to_file , num_page = 1):
    ret = True

    with WandImage(filename=from_file, resolution=150) as pdf:    

        pages = len(pdf.sequence)

        num_page = max (num_page - 1, 0)
        
        if (pages <= num_page):
            ret = False
            return ret

        image = WandImage(
            width=pdf.width,
            height=pdf.height
        )

        image.composite(
            pdf.sequence[num_page],
            top=0,
            left=0
        )

        image.save(filename=to_file)

    return ret
예제 #7
0
def generate_memoir(memoir, art_data=None):
    errors = []
    try:
        if not art_data:
            art_field = getattr(memoir, 'art')
            art_data = art_field.read()
        art_image = Image(file=cStringIO.StringIO(art_data))
    except (BlobError, ValueError):
        errors.append('  Art not saved in memoir.')
        return art_data, None, errors

    try:
        border_image = Image(
            filename=BASE_DIR +
            'starlight/static/extracts/cards_elements/memoir_border.png')
        rarity_image = Image(
            filename=BASE_DIR +
            u'starlight/static/extracts/cards_elements/{}.png'.format(
                memoir.rarity))
    except BlobError:
        errors.append('  Memoir layer image(s) not found.')
        return art_data, None, errors

    art_image.resize(width=border_image.width, height=border_image.height)
    art_image.composite(border_image, left=0, top=0)
    rarity_image.transform(resize='x73')
    art_image.composite(rarity_image,
                        top=(art_image.height - rarity_image.height - 19),
                        left=20)

    art_image.save(filename=BASE_DIR + 'tmp.png')

    return art_data, saveLocalImageToModel(memoir, 'image',
                                           BASE_DIR + 'tmp.png'), errors
예제 #8
0
def generate_memoir_icon(memoir, field_name, rank, base_icon_data=None):
    errors = []
    try:
        if not base_icon_data:
            base_icon_field = getattr(memoir, 'base_icon')
            base_icon_data = base_icon_field.read()
        base_icon_image = Image(file=cStringIO.StringIO(base_icon_data))
    except (BlobError, ValueError):
        errors.append('  Base icon not saved in memoir.')
        return base_icon_data, None, errors

    try:
        border_image = Image(
            filename=BASE_DIR +
            u'starlight/static/extracts/cards_elements/memoir_icon_rank{}.png'.
            format(rank))
        rarity_image = Image(
            filename=BASE_DIR +
            u'starlight/static/extracts/cards_elements/icon_rarity{}.png'.
            format(memoir.rarity))
    except BlobError:
        errors.append('  Icon layer image(s) not found.')
        return base_icon_data, None, errors

    base_icon_image.composite(border_image, left=0, top=0)
    base_icon_image.composite(
        rarity_image,
        top=(base_icon_image.height - rarity_image.height) - 2,
        left=(base_icon_image.width / 2) - (rarity_image.width / 2),
    )

    base_icon_image.save(filename=BASE_DIR + 'tmp.png')

    return base_icon_data, saveLocalImageToModel(memoir, field_name,
                                                 BASE_DIR + 'tmp.png'), errors
예제 #9
0
파일: gulag.py 프로젝트: joazlazer/autbot
def generate(url):
    hdr = {
        'User-Agent': 'Mozilla/5.0',
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
    }
    req = urllib2.Request(url, headers=hdr)
    f = urllib2.urlopen(req)

    im = pilimg.open(f)
    key = ''.join([random.choice(string.ascii_letters) for n in range(10)])
    im.save('res/' + key + ".png", "png")

    with Image(filename='res/%s.png' % key) as img:
        if img.sequence:
            img = Image(image=img.sequence[0])
        img.resize(300, 300)
        with Drawing() as draw:
            draw.fill_color = Color('#f00')
            draw.fill_opacity = 0.4
            draw.rectangle(0, 0, img.width, img.height)

            draw(img)
        with Image(filename='res/generate/gulag.png') as sickle:
            sickle.resize(200, 200)
            img.composite(sickle, 50, 50)
        img.format = 'png'
        img.save(filename='res/gulag.png')
    os.remove('res/' + key + '.png')
예제 #10
0
def generate_sprite(image_dir, images):
    """ (str, list of Image) -> str

    Generate sprites with 4 images

    Returns the name of the generated sprite
    """
    image_width = 160
    image_height = 232
    sprite = None
    left_position = 0
    for image in images:
        i = get_resized_image(image=image, width=image_width, height=image_height)
        if sprite is None:
            if i.height == i.width:
                sprite = Image(width=image_width*4, height=image_width, background=Color("#fff"))
            else:
                sprite = Image(width=image_width*4, height=image_height, background=Color("#fff"))
        sprite.composite(image=i, left=left_position, top=0)
        left_position += image_width
        i.destroy()
    sprite_file = "%s/sprite.jpg" % (image_dir)

    if not isdir(image_dir):
        makedirs(image_dir)

    sprite.save(filename=sprite_file)
    sprite.destroy()

    return sprite_file
예제 #11
0
    def draw(self):
        image = Image(width=100, height=300, background=Color('black'))

        with Image(width=100, height=100, pseudo='xc:white') as rect:
            position = round((math.sin(self.state) + 1) * AMPLITUDE)
            image.composite(rect, top=position)

        return image
예제 #12
0
파일: mask.py 프로젝트: CoffeeKing68/Layers
 def render(self, fresh=False):
     image = Image(width=int(self["width"]), height=int(self["height"]))
     for layer in sorted(self.layers, key=lambda l: l.order):
         if layer.content is not None or isinstance(layer, Template):
             img = layer.render(fresh)
             if img is not None:
                 image.composite(img, left=int(layer["left"] - self["left"]), top=int(layer["top"]- self["top"]))
     return image
예제 #13
0
def convert_file(image_binary):

    with Image(blob=image_binary) as foreground:
        foreground.transform(resize="300x300")
        out = Image(width=1280, height=720, background=Color('white'))
        out.composite(foreground, left=0, top=0)
        out.format = 'PNG'
        return out
예제 #14
0
def CopyImageV(image, count = 1, out=None):
    if out is None:
        out = image
    with Image(filename=image) as img:
        merged = Image(width=img.width, height=img.height * count)
        for i in range(count):
            merged.composite(img, 0, img.height * i)
        merged.save(filename=out)
예제 #15
0
파일: pdf.py 프로젝트: NewAcropolis/api
def extract_first_page(blob):
    pdf = Image(blob=blob, resolution=200)

    image = Image(width=pdf.width, height=pdf.height)

    image.composite(pdf.sequence[0], top=0, left=0)

    return image.make_blob('png')
예제 #16
0
def create_row(imgs,
               offsets,
               gap,
               fixed_width=0,
               caption=None,
               caption_offset=(0, 0)):
    row_width = 0
    i = 0
    row_height = 0

    for img in imgs:
        if isinstance(img, Image):
            row_width += img.width + gap
            row_height = max(img.height, row_height)
        else:
            row_width += offsets[i][0] + gap
        i += 1

    if fixed_width:
        row_width = fixed_width

    row = Image(width=row_width, height=row_height)

    i = 0
    x = 0

    for img in imgs:
        if isinstance(img, Image):
            row.composite(img,
                          left=x + offsets[i],
                          top=(row_height - img.height) / 2)
            x += img.width + offsets[i] + gap
        else:
            (offset_x, offset_y, width, font) = offsets[i]
            row.caption(img,
                        left=x + offset_x,
                        top=offset_y,
                        width=250,
                        height=250,
                        font=font)
            x += width + gap
        i += 1

    if caption:
        caption_font = Font(
            path="%s/source-code-pro/SourceCodePro-Medium.otf" % args.fonts,
            size=14)
        row_w_caption = Image(width=row_width, height=row_height + 20)
        row_w_caption.caption(caption,
                              left=caption_offset[0],
                              top=caption_offset[1],
                              width=1450,
                              height=50,
                              font=caption_font)
        row_w_caption.composite(row, left=0, top=20)
        return row_w_caption
    else:
        return row
예제 #17
0
def show_pdf(file_name):
    imageFromPdf = Image(filename=file_name)
    pages = len(imageFromPdf.sequence)

    image = Image(width=imageFromPdf.width, height=imageFromPdf.height * pages)
    for i in range(pages):
        image.composite(imageFromPdf.sequence[i],
                        top=imageFromPdf.height * i,
                        left=0)
    image.format = "png"
    return image
예제 #18
0
 def shadow(self, x, y, radius=2, sigma=4, fresh=False, color="Black"):
     if fresh or not hasattr(self, "pre_shadow") or self.pre_shadow is None:
         shadow = self.color_overlay(color, fresh=False).clone()
         image = Image(width=int(self.template["width"]),
                       height=int(self.template["height"]))
         image.composite(shadow,
                         int(self["left"]) + x,
                         int(self["top"]) + y)
         image.blur(radius, sigma)
         self.pre_shadow = image
     return self.pre_shadow
예제 #19
0
def create_pil_thumbnail_dict_from_path(file_alias_and_name_tup, *,
                                        thumbnail_width=THUMBNAIL_WIDTH_DEFAULT,
                                        thumbnail_height=THUMBNAIL_HEIGHT_DEFAULT,
                                        out_format=DEFAULT_OUT_FORMAT,
                                        accepted_image_formats=DEFAULT_ACCEPTED_IMG_FORMATS,
                                        accepted_pdf_formats=DEFAULT_PDF_FORMATS):
    """
    Import image or pdf and create a thumbnail in the Pillow library format, made for batch Tkinter use with Pool.
    :Parameters:
        :param tuple file_alias_and_name_tup: tuple containing the return dict key-name and the document file path.
        :param int thumbnail_width: thumbnail width (default is 500)
        :param int thumbnail_height: thumbnail height (default is 300)
        :param str out_format: set the pdf image magick image format used during the pdf-to-image conversion.
        :param dict of strings accepted_image_formats: determines accepted image file endings.
        :param dict of strings accepted_pdf_formats: determines accepted pdf endings.
    :rtype: Dictionary of Dict
    :return dict return_dict: {<file_alias>: {"path": <filename>, "thumbnail": <Pillow Image Object>}}
        file_alias is file_alias_and_name_tup input index 0, filename is file_alias_and_name input index 1.
        Pillow Image Object is the imported image/pdf thumbnail, or None.
    """
    def _convert_pdf_object_with_attributes(pdf_object):
        pdf_object.format = out_format
        pdf_object.background_color = WandCol('white')
        pdf_object.alpha_channel = 'remove'
        pdf_object.resize(thumbnail_width, thumbnail_height)
        image_data = BytesIO()
        pdf_object.save(file=image_data)
        image_data.seek(0)
        converted_image = Image.open(image_data)
        return converted_image

    file_alias, filename = file_alias_and_name_tup
    ending = filename[-4:]
    if ending in accepted_pdf_formats:
        image_in = WandIm(filename=filename)
        pages = len(image_in.sequence)
        if pages > 1:
            h = image_in.height * pages
            w = image_in.width
            img = WandIm(width=w, height=h)
            for i in range(pages):
                img.composite(image_in.sequence[i],
                              top=image_in.height * i,
                              left=0)
            pilim = _convert_pdf_object_with_attributes(img)
        else:
            pilim = _convert_pdf_object_with_attributes(image_in)
    elif ending in accepted_image_formats:
        img = Image.open(filename)
        pilim = img.resize((thumbnail_width, thumbnail_height), Image.ANTIALIAS)
    else:
        pilim = None
    return_dict = {file_alias: {"path": filename, "thumbnail": pilim}}
    return return_dict
예제 #20
0
def gay(img: Image):
    with Image(
            filename=
            f"{os.path.dirname(os.path.realpath(__file__))}\\api_assets\\gay.jpg"
    ) as gay:
        img.transform_colorspace("gray")
        img.transform_colorspace("rgb")
        gay.transparentize(.50)
        gay.sample(img.width, img.height)
        img.composite(gay, 0, 0)
    return img
예제 #21
0
 def render_boundary(self):
     image = Image(width=int(self["width"]),
                   height=int(self["height"]),
                   background=Color("Transparent"))
     for layer in sorted(self.layers, key=lambda l: l.order):
         img = layer.render_boundary()
         if img is not None:
             image.composite(img,
                             left=int(layer["left"]),
                             top=int(layer["top"]))
     return image
예제 #22
0
def pdf_to_thumbnail(pdf_url_path='https://arxiv.org/pdf/1902.10162v2.pdf',
                     output_image_filename='out.png'):
    tmp_dir = tempfile.gettempdir()
    wget_output = os.path.join(tmp_dir, 'out_wget.pdf')
    wget.download(pdf_url_path, out=wget_output)
    input_pdf = PdfFileReader(open(wget_output, 'rb'))
    assert input_pdf.numPages > 0
    output = PdfFileWriter()
    output.addPage(input_pdf.getPage(0))
    wget_output_1page = os.path.join(tmp_dir, 'out_wget_1page.pdf')
    with open(wget_output_1page, 'wb') as outputStream:
        output.write(outputStream)

    image_from_df = WAND_Image(filename=wget_output_1page, resolution=300)
    pages = len(image_from_df.sequence)
    # print(pages)
    image = WAND_Image(width=image_from_df.width,
                       height=image_from_df.height * pages)
    for i in range(pages):
        image.composite(image_from_df.sequence[i],
                        top=image_from_df.height * i,
                        left=0)
    # image.background_color = Color('transparent')
    # image.type = 'grayscale'
    image.format = 'png'
    img_output_transparent = os.path.join(tmp_dir, 'out_wget_1page.png')
    image.save(filename=img_output_transparent)
    # display(image)

    img = PIL_Image.open(open(img_output_transparent, 'rb'))

    def remove_transparency(im, bg_colour=(255, 255, 255)):
        # Only process if image has transparency (http://stackoverflow.com/a/1963146)
        if im.mode in ('RGBA', 'LA') or (im.mode == 'P'
                                         and 'transparency' in im.info):

            # Need to convert to RGBA if LA format due to a bug in PIL (http://stackoverflow.com/a/1963146)
            alpha = im.convert('RGBA').split()[-1]

            # Create a new background image of our matt color.
            # Must be RGBA because paste requires both images have the same format
            # (http://stackoverflow.com/a/8720632  and  http://stackoverflow.com/a/9459208)
            bg = PIL_Image.new('RGBA', im.size, bg_colour + (255, ))
            bg.paste(im, mask=alpha)
            return bg

        else:
            return im

    img = remove_transparency(img)
    output_path = os.path.join(tmp_dir, output_image_filename)
    img.save(output_path)
    return output_path
예제 #23
0
파일: BMFont.py 프로젝트: 4Enjoy/ADLib
def resizeCanvas(image, new_width, new_height):
    if image.width > new_width:
        image.crop(0, 0, new_width, image.height)
    if image.height > new_height:
        image.crop(0, 0, image.width, new_height)

    if image.width == new_width and image.height == new_height:
        return image

    canvas = Image(width=new_width, height=new_height)
    canvas.composite(image, 0, 0)
    return canvas
예제 #24
0
파일: composer.py 프로젝트: ikol/PURIKURA
def compose(conn, ready_queue, images, config):
    from wand.image import Image
    from wand.color import Color
    import os

    # get all the images and overlay them
    layers = []
    while len(layers) < images:
        try:
            this_config = ready_queue.get()
            layers.append((this_config['name'], this_config))
        except Queue.Empty:
            pass

    # the base to the image we are producing
    base = Image(width=config['width'],
                 height=config['height'],
                 background=Color(config['background']))

    cache = {}

    for name, image_config in sorted(layers):
        x, y, w, h = image_config['area']
        print name, x, y, w, h
        try:
            temp_image = cache[image_config['filename']]
        except KeyError:
            temp_image = Image(filename=image_config['filename'])
            cache[image_config['filename']] = temp_image
        base.composite(temp_image, x, y)

    # save it!
    new_path = 'composite.png'

    for image in cache.values():
        image.close()

    # append a dash and numberal if there is a duplicate
    if os.path.exists(new_path):
        i = 1
        root, ext = os.path.splitext(new_path)
        new_path = "{0}-{1:04d}{2}".format(root, i, ext)
        while os.path.exists(new_path):
            i += 1
            new_path = "{0}-{1:04d}{2}".format(root, i, ext)

    base.format = 'png'
    base.save(filename=new_path)
    base.close()

    conn.send(new_path)
    conn.close()
예제 #25
0
def combine_layers(images, filename):
    combo = None
    for index, im in enumerate(images):
        if not isinstance(combo, Image):
            combo = Image(filename=im)
        if index == len(images) - 1:
            break
        else:
            im2 = images[index + 1]
            im2 = Image(filename=im2)
            combo.composite(im2, left=0, top=0)
    combo.save(filename=filename)
    combo.close()
예제 #26
0
def convert_pdf_to_png(filenameVal):
    pdf = Image(filename=filenameVal, resolution=200)

    pages = len(pdf.sequence)

    image = Image(width=pdf.width, height=pdf.height * pages)

    for i in xrange(pages):
        image.composite(pdf.sequence[i], top=pdf.height * i, left=0)
    image.background_color = Color("white")
    image.alpha_channel = 'remove'
    image.save(filename="out.png")
    return remove_points_from_image(filenameVal)
예제 #27
0
 def create_thumbnail(self):
     """ Create a jpg version of the pdf frontpage """
     pdf_name = self.pdf.path
     cover_page = pdf_name.replace('.pdf',
                                   '.jpg').replace('pdf/', 'pdf/covers/')
     img = WandImage(filename=pdf_name + '[0]', resolution=60)
     bg = WandImage(width=img.width,
                    height=img.height,
                    background=Color('white'))
     bg.composite(img, 0, 0)
     bg.save(filename=cover_page)
     self.cover_page = cover_page
     self.save()
예제 #28
0
def remove_image_transparency(img):
    """
    Remove any transparency layer from the given image and return the result.
    """
    if img.alpha_channel:
        bg = WandImage(width=img.width,
                       height=img.height,
                       background=WandColor('white'))
        bg.composite(img, 0, 0)
        img.destroy()
        img = bg

    return img
예제 #29
0
def combine_layers(images, filename):
    combo = None
    for index, im in enumerate(images):
        if not isinstance(combo, Image):
            combo = Image(filename=im)
        if index == len(images) - 1:
            break
        else:
            im2 = images[index + 1]
            im2 = Image(filename=im2)
            combo.composite(im2, left=0, top=0)
    combo.save(filename=filename)
    combo.close()
예제 #30
0
파일: giraffe.py 프로젝트: steder/giraffe
def overlay_that(img, bucket=None, path=None, overlay=None, bg=None, w=None, h=None, x=None, y=None):
    if bucket:
        key = get_object_or_none(bucket, path)
        overlay_content = key.content
    else:
        try:
            resp = requests.get(overlay)
        except (ConnectionError) as e:
            print(e)
            raise
        else:
            overlay_content = resp.content

    if overlay_content:
        if w is not None and h is not None and x is not None and y is not None:
            pass
        else:
            w, h, x, y = 294, 336, 489, 173

        image_orientation = 'square'
        overlay_orientation = 'square'

        if img.width > img.height:
            image_orientation = 'landscape'
        elif img.width < img.height:
            image_orientation = 'portrait'

        overlay_img = stubbornly_load_image(overlay_content, None, None)

        if overlay_img.width > overlay_img.height:
            overlay_orientation = 'landscape'
        elif overlay_img.width < overlay_img.height:
            overlay_orientation = 'portrait'

        overlay_width, overlay_height = overlay_img.width, overlay_img.height
        width, height = w, h
        size = "{}x{}^".format(width, height)
        #crop_size = "{}x{}!".format(width, height)
        img.transform(resize=size)
        #w_offset = max((img.width - width) / 2, 0)
        #h_offset = max((img.height - height) / 2, 0)
        c = Color('#' + bg)
        background = Image(width=overlay_width, height=overlay_height, background=c)
        background.composite(img, x, y)
        img = background

        # Overlay canvas:
        img.composite(overlay_img, 0, 0)
    else:
        raise Exception("Couldn't find an overlay file for bucket '{}' and path '{}' (overlay='{}')".format(bucket, path, overlay))
    return img
예제 #31
0
파일: shadow.py 프로젝트: quantum5/win2xcur
def apply_to_image(image: BaseImage, *, color: str, radius: float,
                   sigma: float, xoffset: float, yoffset: float) -> Image:
    xoffset = round(xoffset * image.width)
    yoffset = round(yoffset * image.height)
    new_width = image.width + 3 * xoffset
    new_height = image.height + 3 * yoffset

    opacity = Image(width=new_width, height=new_height, pseudo='xc:white')
    opacity.composite(image.channel_images['opacity'],
                      left=xoffset,
                      top=yoffset)
    opacity.gaussian_blur(radius * image.width, sigma * image.width)
    opacity.negate()
    opacity.modulate(50)

    shadow = Image(width=new_width, height=new_height, pseudo='xc:' + color)
    shadow.composite(opacity, operator='copy_opacity')

    result = Image(width=new_width, height=new_height, pseudo='xc:transparent')
    result.composite(image)
    result.composite(shadow, operator='difference')

    trimmed = result.clone()
    trimmed.trim(color=Color('transparent'))
    result.crop(width=max(image.width, trimmed.width),
                height=max(image.height, trimmed.height))
    return result
예제 #32
0
파일: lib.py 프로젝트: natet/vb_textblaster
def genTextPNG(text,font="/usr/share/fonts/type1/gsfonts/c059016l.pfb",fsize=48):
	#put these here so that they are not imported until needed
	from wand.image import Image
	from wand.font import Font
	from wand.color import Color

	# convert -size 1000x180 xc:transparent -fx 0 -channel A -fx 'cos(0.6*pi*(i/w-0.5))-0.0' background.png
	img=Image(filename="background1280.png")
	fontwhite=Font(path=font,color=Color("white"),size=fsize,antialias=True)
	fontblack=Font(path=font,color=Color("black"),size=fsize,antialias=True)
	img.caption(text,font=fontblack,gravity='center',left=8,top=8)
	img.caption(text,font=fontwhite,gravity='center')
	final = Image(width=1280,height=720)
	final.composite(img,0,530)
	return final
예제 #33
0
 def pdf_not_found():
     """Creates an error frontpage"""
     img = WandImage(width=400, height=600,)
     msg = 'ERROR:\n{}\nnot found on disk'.format(self.pdf.name)
     with Drawing() as draw:
         draw.text_alignment = 'center'
         draw.text(img.width // 2, img.height // 3, msg)
         draw(img)
     background = WandImage(
         width=img.width,
         height=img.height,
         background=Color('white'))
     background.format = 'jpeg'
     background.composite(img, 0, 0)
     return background
예제 #34
0
def _gay(img: Image):
    if os.name == 'nt':
        slash = "\\"
    else:
        slash = "/"
    with Image(
            filename=
            f"{os.path.dirname(os.path.realpath(__file__))}{slash}image_assets{slash}gay.jpg"
    ) as gay:
        img.transform_colorspace("gray")
        img.transform_colorspace("rgb")
        gay.transparentize(.50)
        gay.sample(img.width, img.height)
        img.composite(gay, 0, 0)
    return img
예제 #35
0
 def create_thumbnail(self):
     """ Create a jpg version of the pdf frontpage """
     pdf_name = self.pdf.path
     cover_page = pdf_name.replace(
         '.pdf', '.jpg').replace(
         'pdf/', 'pdf/covers/')
     img = WandImage(filename=pdf_name + '[0]', resolution=60)
     bg = WandImage(
         width=img.width,
         height=img.height,
         background=Color('white'))
     bg.composite(img, 0, 0)
     bg.save(filename=cover_page)
     self.cover_page = cover_page
     self.save()
예제 #36
0
def error_image(msg, width=420, height=600):
    """Creates an error frontpage"""
    width, height = int(width), int(height)
    img = WandImage(width=width, height=height)
    with Drawing() as draw:
        draw.text_alignment = 'center'
        draw.text(img.width // 2, img.height // 3, msg)
        draw(img)
    background = WandImage(
        width=img.width,
        height=img.height,
        background=Color('white'),
    )
    background.format = 'jpeg'
    background.composite(img, 0, 0)
    return background
예제 #37
0
def error_image(msg, width=420, height=600):
    """Creates an error frontpage"""
    width, height = int(width), int(height)
    img = WandImage(width=width, height=height)
    with Drawing() as draw:
        draw.text_alignment = 'center'
        draw.text(img.width // 2, img.height // 3, msg)
        draw(img)
    background = WandImage(
        width=img.width,
        height=img.height,
        background=Color('white'),
    )
    background.format = 'jpeg'
    background.composite(img, 0, 0)
    return background
예제 #38
0
def multikek(filename, extension):
    w, h, canvasL = kekify("-l", filename, extension, None)
    w, h, canvasR = kekify("-r", filename, extension, None)
    w, h, canvasT = kekify("-t", filename, extension, None)
    w, h, canvasB = kekify("-b", filename, extension, None)
    big_canvas = Image()
    big_canvas.blank(w * 2, h * 2)
    big_canvas.composite(canvasL, 0, 0)
    big_canvas.composite(canvasR, w, 0)
    big_canvas.composite(canvasT, 0, h)
    big_canvas.composite(canvasB, w, h)
    canvasL.close()
    canvasR.close()
    canvasT.close()
    canvasB.close()
    return big_canvas
예제 #39
0
파일: yapot.py 프로젝트: akash0675/yapot
def _save_page_image(pdf_filename, image, thumb_filename,
        make_thumb, thumb_size, thread_number, verbose=False):

    success = False
    image_filename = ''
    if True:
    #try:

        if verbose == True:
            print "{0}: Saving off PDF image ...".format(thread_number)

        try:
          image_filename = '{0}.tiff'.format(pdf_filename)
          bg = WandImage(width=image.width, height=image.height, background=Color("white"))
          bg.composite(image, 0, 0)
          bg.clone().save(
            filename = image_filename,
          )
        except Exception, ex:
          print ex
        #image.clone().save(
        #    filename=image_filename
        #)

        if verbose == True:
            print "{0}: Done saving off PDF image.".format(thread_number)

        if make_thumb == True:

            if verbose == True:
                print "{0}: Making thumb nail image: '{1}' ...".format(thread_number, thumb_filename)

            FNULL = open(os.devnull, 'w')
            cli_call = [
                'convert',
                '-resize',
                '{0}x{0}'.format(thumb_size),
                image_filename,
                thumb_filename,
            ]
            subprocess.call(
                cli_call,
                stdout=FNULL,
                stderr=subprocess.STDOUT
            )

        success = True
예제 #40
0
def writeImageNoWarp(pdf, out, resolution=pdfDense, trim=True):
    with Image(filename=pdf, resolution=resolution) as pdf:

        pages = len(pdf.sequence)
        height = 0
        width = 0
        for j in range(pages):
            ## Go through the sequence and trim them individually
            with pdf.sequence.index_context(j):
                if trim:
                    pdf.trim()
                    height += pdf.height + 10
                    if (width < pdf.width):
                        width = pdf.width
                else:
                    width = pdf.width
                    height = pdf.height

        i = Image(width=width, height=height)

        height = [r.height for r in pdf.sequence]
        height = height[::-1]
        height.append(0)
        height = height[::-1]
        width = [math.floor((width - r.width) / 2) for r in pdf.sequence]

        for j in range(pages):
            i.composite(pdf.sequence[j], top=height[j] + j * 10, left=width[j])
        i.background_color = Color('white')  # Set white background.
        i.alpha_channel = 'remove'
        if trim:  ## This is necessary because of stacked charts (above)
            i.trim()
        i.sharpen(radius=5.0, sigma=5.0)
        i.normalize()
        i.quantize(16, dither=False)
        i.compression_quality = 00
        i.save(filename=out.replace(".png", ".png8"))
        tmp = out.replace(".png", "") + "*"
        #out = glob.glob(tmp)
        if (os.system("rename .png8 .png %s*" % tmp)):
            print("Error in saving file.")
        if (os.system("optipng -quiet %s*" % tmp)):
            print("Error in optipng.")
        commstr = 'cwebp -quiet -lossless -z 9 -metadata exif %s -o %s' % (
            out, out.replace(".png", ".webp"))
        if (os.system(commstr)):
            print("Error in cwebp")
예제 #41
0
 def pdf_not_found():
     """Creates an error frontpage"""
     img = WandImage(
         width=400,
         height=600,
     )
     msg = 'ERROR:\n{}\nnot found on disk'.format(self.pdf.name)
     with Drawing() as draw:
         draw.text_alignment = 'center'
         draw.text(img.width // 2, img.height // 3, msg)
         draw(img)
     background = WandImage(width=img.width,
                            height=img.height,
                            background=Color('white'))
     background.format = 'jpeg'
     background.composite(img, 0, 0)
     return background
예제 #42
0
def make_layer(layer_info, font_family):
    if ('text' in layer_info.keys()):
        graphic = make_layer_text(layer_info, font_family)
    elif ('image' in layer_info.keys()):
        graphic = make_layer_image(layer_info)
    else:
        graphic = new_blank_png(100, 100, Color('blue'))

    # Was there any padding??
    #
    if ('padding' in layer_info.keys()):
        seq = layer_info['padding'].split()
        (top_offset, pad_r, pad_b, left_offset) = tuple([int(num) for num in seq])
        old_graphic = graphic
        old_width  = old_graphic.width
        new_width  = old_width + pad_r + left_offset
        old_height = old_graphic.height
        new_height = old_height + top_offset + pad_b
        if 'box-color' in layer_info.keys():
            new_graphic = Image(width=new_width, height=new_height,
                background=Color(layer_info['box-color']))
        else:
            new_graphic = Image(width=new_width, height=new_height,
                background=None)
        new_graphic.composite(old_graphic, left_offset, top_offset)
        graphic = new_graphic

    # Was there an opacity setting??
    #
    if ('opacity' in layer_info.keys()):
        val = layer_info['opacity']
        match = re.match(r"(\d*(\.d*)?)%$", val)
        if match:
            p = float(match.group(1))
            p = p / 100.0
            gs = int(255 * p)
            color_string = "rgb(%d,%d,%d)" % (gs, gs, gs)
            opacity_mask = Image(width=graphic.width, height=graphic.height,
                background=Color(color_string))
            graphic.composite_channel(channel='all_channels', image=opacity_mask,
                operator='copy_opacity')
                
    return graphic
예제 #43
0
    def set_image(self, binary):
        self.binary = binary
        with Image(blob=self.binary, resolution=150) as img:
            self.extension = img.format.lower()
            flattened = Image(background=Color("white"),
                height=img.height, width=img.width)
            flattened.composite(img, left=0, top=0)
            flattened.format = "jpeg"
            flattened.compression_quality = 50

            thumbnail = flattened.clone()
            thumbnail.transform(resize='150x200>')
            self.thumbnail = thumbnail.make_blob()

            preview = flattened.clone()
            preview.gaussian_blur(radius=1, sigma=0.5)
            preview.transform(resize='612x792>')
            self.preview = preview.make_blob()
        self.save()
예제 #44
0
def pdf_to_image(pdf, page=1, size=800, file_format='jpeg', quality=80):
    """Creates a image file from pdf file"""
    try:
        pdf.open()
    except Exception as e:
        raise e
    else:
        # do this while the pdf is open
        reader = PyPDF2.PdfFileReader(pdf, strict=False)
        writer = PyPDF2.PdfFileWriter()
        page_content = reader.getPage(page - 1)
        box = page_content.cropBox
        dims = [float(a - b) for a, b in zip(box.upperRight, box.lowerLeft)]
        scaleby = size / max(dims)
        dims = [int(d * scaleby) for d in dims]
        # resize_page(page_content, size)
        writer.addPage(page_content)
        outputStream = BytesIO()
        writer.write(outputStream)
        outputStream.seek(0)
    finally:
        pdf.close()
    # put content of page in a new image
    foreground = WandImage(
        blob=outputStream,
        format='pdf',
        resolution=int(1.6 * 72 * scaleby),
    )
    # make sure the color space is correct.
    # this prevents an occational bug where rgb colours are inverted
    foreground.type = 'truecolormatte'
    foreground.resize(*dims, 25)
    # white background
    background = WandImage(
        width=foreground.width,
        height=foreground.height,
        background=Color('white')
    )
    background.format = file_format
    background.composite(foreground, 0, 0)
    background.compression_quality = quality
    return background
예제 #45
0
 def pdf_frontpage_to_image():
     reader = PyPDF2.PdfFileReader(self.pdf.file, strict=False)
     writer = PyPDF2.PdfFileWriter()
     first_page = reader.getPage(0)
     writer.addPage(first_page)
     outputStream = BytesIO()
     writer.write(outputStream)
     outputStream.seek(0)
     img = WandImage(
         blob=outputStream,
         format='pdf',
         resolution=60,
     )
     background = WandImage(
         width=img.width,
         height=img.height,
         background=Color('white'))
     background.format = 'jpeg'
     background.composite(img, 0, 0)
     return background
예제 #46
0
	def process(lines, name, out_file):
		#	здесь кусок про соединение строк в одну, если последний символ '/'
		imploded = []
		curline = ''
		for line in lines:
			curline += line
			if len(curline) > 0 and curline[-1] != '/':
				imploded.append(curline)
				curline = ''
			else:
				curline = curline[:-1]
		imploded.append(curline)
		lines = imploded
		
		#	здесь каждая строка кода превращается в картинку
		staves = []
		for line in lines:
			stave_line = LineMaker.process(line)
			if stave_line is not None:
				staves.append(stave_line)
		
		#	здесь готовим основу, в которую будем все размещать
		max_width = max(map(lambda x: x.width, staves)) if len(staves) > 0 else 1
		max_height = (Config.draw_center*2 + 1) * len(staves)
		max_height += 30 if (len(name) > 0) else 0
		tabl_image = Image(width=max_width, height=max_height, 
			background=Color('white'))
		
		#	здесь мы готовим отрисованный титл (будет вверху)
		title = TablMaker.make_title(name, max_width)
		if title is not None:
			tabl_image.composite(title, 0, 0)
			ind = title.height
		else:
			ind = 0
		
		for stave in staves:
			tabl_image.composite(stave, 0, ind)
			ind += (Config.draw_center*2 + 1)
		
		tabl_image.save(filename=out_file)
예제 #47
0
def preview(pdfpath, outpath, croph):
  """
  @arg pdfpath input pdf path
  @arg outpath output screeshot file path
  @arg croph percentage of the page height to crop at
  """
  try:
    with Image(filename=pdfpath) as imgs:
      for imgidx, img in enumerate(imgs.sequence):
        w, h = img.width, img.height
        h = int(croph * h)
        img.crop(0, 0, width=w, height=h)

        newimg = Image(width=w, height=h, background=Color("white"))
        newimg.composite(img, 0, 0)
        newimg.convert("png")
        newimg.save(filename=outpath)
        return True
  except Exception as err:
    print err
    return False
예제 #48
0
def create_row(imgs, offsets, gap, fixed_width=0, caption=None, caption_offset=(0,0)):
	row_width = 0
	i = 0
	row_height = 0

	for img in imgs:
		if isinstance(img, Image):
			row_width += img.width + gap
			row_height = max(img.height, row_height)
		else:
			row_width += offsets[i][0] + gap
		i += 1

	if fixed_width:
		row_width = fixed_width

	row = Image(width=row_width, height=row_height)

	i = 0
	x = 0

	for img in imgs:
		if isinstance(img, Image):
			row.composite(img, left=x + offsets[i], top=(row_height - img.height) / 2)
			x += img.width + offsets[i] + gap
		else:
			(offset_x, offset_y, width, font) = offsets[i]
			row.caption(img, left=x + offset_x, top=offset_y, width=250, height=250, font=font)
			x += width + gap
		i += 1

	if caption:
		caption_font = Font(path="%s/source-code-pro/SourceCodePro-Medium.otf" % args.fonts, size=14)
		row_w_caption = Image(width=row_width, height=row_height+20)
		row_w_caption.caption(caption, left=caption_offset[0], top=caption_offset[1],
								width=1450, height=50, font=caption_font)
		row_w_caption.composite(row, left=0, top=20)
		return row_w_caption
	else:
		return row
예제 #49
0
def create_matches(catcierge_json, output_file, args):

	match_count = catcierge_json["match_group_count"]
	match_imgs = []
	total_width = 0
	total_height = 0
	i = 1

	# All paths in the json are relative to this.
	base_path = os.path.dirname(args.json)

	for match in catcierge_json["matches"][:match_count]:

		step_count = match["step_count"]
		img_paths = []

		for step in match["steps"][:step_count]:
			img_paths.append(os.path.join(base_path, step["path"]))

		img = compose_adaptive_prey(img_paths=img_paths,
				gap=5,
				description=match["description"],
				caption="Match %d" % i)

		total_width += img.width
		total_height = max(total_height, img.height)
		match_imgs.append(img)
		i += 1

	fimg = Image(width=total_width, height=total_height)

	x = 0
	for img in match_imgs:
		fimg.composite(img, left=x, top=0)
		x += img.width

	return fimg
예제 #50
0
def screenshots(pdfpath, h=200):
  #dirpath = os.path.join(os.path.dirname(os.path.dirname(pdfpath)), "imgs")
  dirpath = IMGROOT
  fprefix = os.path.splitext(os.path.basename(pdfpath))[0]
  print "screenshots for %s" % fprefix
  ret = []

  with Image(filename=pdfpath) as imgs:
    for imgidx, img in enumerate(imgs.sequence):
      w = int(h * img.width / img.height)
      tosave = Image(width=img.width, height=img.height, background=Color("white"))
      tosave.composite(img, 0, 0)
      tosave.convert('png')
      tosave.resize(w, h, filter='lagrange', blur=.35)

      imgname = "%s_%02d.png" % (fprefix, imgidx)
      imgpath = os.path.join(dirpath, imgname)
      tosave.save(filename=imgpath)

      ret.append(dict(
        imgpath=imgpath,
        imgidx=imgidx
      ))
  return ret
class GeneratePreviewImage:

    def __init__(self):
        self.background = Image(filename = settings.BASE_DIR + '/background.jpg')
        self.logo = Image(filename = settings.BASE_DIR + '/logo.png')
        self.montageWidth = 600
        self.montageHeight = 315
        
        
    def generatePreviewImage(self, image1Url, image2Url):
        image1 = Image(filename = image1Url)
        self.resizeImage(image1, self.montageWidth / 2, self.montageHeight)
        
        image2 = Image(filename = image2Url)
        self.resizeImage(image2, self.montageWidth / 2, self.montageHeight)
        
        self.background.composite(image1, int(self.montageWidth / 4. - image1.width / 2.), int(self.montageHeight / 2. - image1.height / 2.))
        self.background.composite(image2, int(self.montageWidth / 4. - image2.width / 2.) + self.montageWidth / 2, int(self.montageHeight / 2. - image2.height / 2.))
        
        self.background.composite(self.logo, 0, 0)
        
        self.background.save(filename = settings.BASE_DIR + '/preview.jpg')
    
    def resizeImage(self, image, desiredWidth, desiredHeight):
        originWidth = image.width
        originHeight = image.height
        originRatio = originWidth / float(originHeight)
        
        finalWidth = desiredWidth
            
        finalHeight = finalWidth / originRatio
        if (finalHeight > desiredHeight):
            finalHeight = desiredHeight
            finalWidth = finalHeight * originRatio    
	
        image.resize(int(finalWidth), int(finalHeight))
예제 #52
0
파일: BMFont.py 프로젝트: 4Enjoy/ADLib
    def saveToFile(self, output_dir, file_name, texture_name, texture_max_width=512, margin=2):
        y_offset = 0
        current_row_height = 0
        current_row_width = 0

        line_height = 0

        max_width = 1
        max_height = 1

        symbols = []

        for node in self._image_list:
            image = node["image"]
            w = image.width + margin * 2
            h = image.height + margin * 2

            if current_row_width + w > texture_max_width:
                if current_row_width > max_width:
                    max_width = current_row_width

                y_offset = y_offset + current_row_height
                current_row_width = 0
                current_row_height = 0

            if h > current_row_height:
                current_row_height = h
                if current_row_height > line_height:
                    line_height = current_row_height

                if max_height < current_row_height + y_offset:
                    max_height = current_row_height + y_offset

            x = current_row_width
            y = y_offset
            symbols.append({"node": node, "x": x + margin, "y": y + margin})
            current_row_width += w

        if current_row_width > max_width:
            max_width = current_row_width

        texture = Image(width=max_width, height=max_height)
        for info in symbols:
            texture.composite(info["node"]["image"], info["x"], info["y"])

        texture.save(filename=os.path.join(output_dir, texture_name))

        f = open(os.path.join(output_dir, file_name), "w")
        f.write(
            'info face="Arial" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 outline=0\n'
        )
        f.write(
            "common lineHeight={line_height} base=26 scaleW={width} scaleH={height} pages=1 packed=0 alphaChnl=1 redChnl=0 greenChnl=0 blueChnl=0\n".format(
                line_height=line_height, width=max_width, height=max_height
            )
        )
        f.write('page id=0 file="{texture}"\n'.format(texture=texture_name))
        f.write("chars count={0}\n".format(len(symbols)))

        for info in symbols:
            f.write(
                "char id={char_id}	x={x}	y={y}	width={width}	height={height}	xoffset=0	yoffset=0	xadvance={xadvance}	page=0	chnl=15\n".format(
                    char_id=info["node"]["char"],
                    x=info["x"],
                    y=info["y"],
                    width=info["node"]["image"].width,
                    height=info["node"]["image"].height,
                    xadvance=info["node"]["image"].width,
                )
            )
        f.close()
예제 #53
0
draw.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOFL/TTF/Lato-Bla.ttf'
draw.font_size = 36
draw.fill_color = Color('black')
metrics_02 = draw.get_font_metrics(dummy_image, "CV", False)

image_01 = Image(width=int(metrics_01.text_width),
    height=int(metrics_01.text_height), background=None)
draw_01 = Drawing()
draw_01.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOFL/TTF/Lato-Reg.ttf'
draw_01.font_size = 36
draw_01.fill_color = Color('black')
draw_01.text(0, int(metrics_01.text_height), "21")
draw_01(image_01)

image_02 = Image(width=int(metrics_02.text_width),
    height=int(metrics_02.text_height), background=None)
draw_02 = Drawing()
draw_02.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOFL/TTF/Lato-Bla.ttf'
draw_02.font_size = 36
draw_02.fill_color = Color('black')
draw_02.text(0, int(metrics_02.text_height), "CV")
draw_02(image_02)

image = Image(width=int(metrics_01.text_width + metrics_02.text_width),
    height=int(metrics_02.text_height), background=None)
image.composite(image_01, 0, 0)
image.composite(image_02, int(metrics_01.text_width), 0)

image.save(filename="_00.png")
        xtiles = int(math.ceil(math.sqrt(len(tiles))))
        ytiles = int(math.ceil(len(tiles) / xtiles))
        if scale_factor != 1.0:
            width = int(math.ceil(width * scale_factor))
            height = int(math.ceil(height * scale_factor))
        print "{} tiles - {}x{}".format(len(tiles),xtiles,ytiles)
        print "Width: " + str(width)
        print "Height: " + str(height)
        
        dest = Image(width = width * xtiles,
                     height = height * ytiles,
                     format = "RGBA",
                     background = Color("RGBA(0,0,0,0)"))

        for i, row in enumerate(tiles):
            filename, x, y, w, h = row
            src_img = source.clone()
            src_img.crop(left=x, top=y, width=w, height=h)
            if scale_factor != 1.0:
                h = int(math.ceil(h * scale_factor))
                w = int(math.ceil(w * scale_factor))
                src_img.resize(w, h)
            left_padding = width - w if "Left" in filename else 0
            (ypos, xpos) = divmod(i, xtiles)
            #print "Placed object at {}, {}".format(xpos, ypos)
            dest.composite(src_img,
                           left = xpos * width + left_padding,
                           top = ypos * height)

        dest.save(filename = groupname + ".png")
for user in reader:
    background = Image(filename="fond.png")
    values.update(user)
    result = ""
    if values["id"]:
        result = requests.get("%s/?key=%s&steamids=%s&format=json" % (STEAM_API_URL, STEAM_API_KEY, values["id"]))
        data = json.loads(result.text)
        if "personaname" in data["response"]["players"][0]:
            personaname = data["response"]["players"][0]["personaname"][:20]
        if "avatar" in data["response"]["players"][0]:
            avatar = data["response"]["players"][0]["avatar"]
            loadedimg = urlopen(avatar)
            userimg = Image(file=loadedimg)
            loadedimg.close()
            rankimg = Image(filename="rank%s.png" % values["rank"])
            background.composite(userimg, 6, 6)
            background.composite(rankimg, 224, 6)
        background.format = "png"
        background.save(filename="%s.png" % values["id"])
        font = ImageFont.truetype("UbuntuMono-R.ttf", 17)
        img = ImagePIL.open("%s.png" % values["id"])
        draw = ImageDraw.Draw(img)
        draw.text((44, 23), "%s" % (personaname), (255, 255, 255), font=font)
        draw = ImageDraw.Draw(img)
        draw.text((44, 3), "%s" % (values["hfr"][:20]), (241, 143, 24), font=font)
        draw = ImageDraw.Draw(img)
        img.save("%s.png" % values["id"])
        print "%s's image created." % (values["hfr"])
quit()
def renderAnimation(animationName, numFrames):
    print("Rendering animation: " + animationName)
    dirToFramesMapping = dict()
    
    animationDirectory =  workingDirectory + animationName + "/"
 
    for key, value in directions.items():
        directory = animationDirectory + value + "/"
        frames = []
        
        for i in range(0, numFrames):
            frameBuffer = Image(filename=(directory + animationName + "_" + str(i + 1) + ".png"));
            
            if(frameBuffer.width > frameWidth):
                frameBuffer.crop(int((frameBuffer.width - frameWidth)/2), 0, width=frameWidth, height=frameBuffer.height)
        
            if(frameBuffer.height > frameHeight):
                frameBuffer.crop(0, int((frameBuffer.height - frameHeight)/2), frameBuffer.width, height=frameHeight)
        
            newBuffer = Image(width=frameWidth, height=frameHeight)
            newBuffer.composite(frameBuffer, int((newBuffer.width - frameBuffer.width) / 2), int((newBuffer.height - frameBuffer.height) / 2))
            frameBuffer = newBuffer
        
            frames.append(frameBuffer)
            
        dirToFramesMapping[key] = frames
    
    directionAnimations = dict()
    
    for key, value in dirToFramesMapping.items():
        directionAnimationBuffer = Image(width=frameWidth * numFrames, height=frameHeight)
        for i in range(0, len(value)):
            frameBuffer = value[i]
            directionAnimationBuffer.composite(frameBuffer, i * frameWidth, 0)
         
        directionAnimations[key] = directionAnimationBuffer
    
    animation = Image(width=frameWidth * numFrames, height=frameHeight * len(directions))
    animation.composite(directionAnimations["n"], 0, 0)
    animation.composite(directionAnimations["ne"], 0, frameHeight)
    animation.composite(directionAnimations["e"], 0, frameHeight * 2)
    animation.composite(directionAnimations["se"], 0, frameHeight * 3)
    animation.composite(directionAnimations["s"], 0, frameHeight * 4)
    animation.composite(directionAnimations["sw"], 0, frameHeight * 5)
    animation.composite(directionAnimations["w"], 0, frameHeight * 6)
    animation.composite(directionAnimations["nw"], 0, frameHeight * 7)
    
    animation.save(filename=animationDirectory + animationName + ".png")
예제 #57
0
def compose_adaptive_prey(img_paths=None, match_json=None, gap=5, horizontal_gap=5, description=None, caption="Catcierge"):

	img = Image(width=600, height=1124, background=Color("#8A968E"))

	#print("Font path: %s" % args.fonts)

	font = Font(path="%s/source-code-pro/SourceCodePro-Medium.otf" % args.fonts, size=64)
	font_title = Font(path="%s/alex-brush/AlexBrush-Regular.ttf" % args.fonts, size=64)
	font_math = Font(path="%s/Asana-Math/Asana-Math.otf" % args.fonts, size=64)


	imgs = []
	assert (img_paths and (len(img_paths) > 0)) or match_json, \
		"Missing either a list of input image paths or a match json"

	if not img_paths or len(img_paths) == 0:
		step_count = match_json["step_count"]

		for step in match_json["steps"][:step_count]:
			print("Step: %s" % step["name"])
			img_paths.append(step["path"])

	# TODO: Allow any matcher type and number of images...	
	assert len(img_paths) == 1 or len(img_paths) == 11, \
		"Invalid number of images %d, expected 2 or 11" % len(img_paths)

	for img_path in img_paths:
		#print img_path
		imgs.append(Image(filename=img_path))

	mpos = lambda w: (img.width - w) / 2

	if len(img_paths) == 1:
		img.caption(caption, left=(img.width - 250) / 2, top=5, width=250, height=100, font=font_title)
		img.composite(imgs[0], left=mpos(imgs[0].width), top=120)
		return img

	orgimg = imgs[0]	# Original image.
	detected = imgs[1]	# Detected cat head roi. 
	croproi = imgs[2]	# Cropped/extended roi.
	globalthr = imgs[3]	# Global threshold (inverted).
	adpthr = imgs[4]	# Adaptive threshold (inverted).
	combthr = imgs[5]	# Combined threshold.
	opened = imgs[6]	# Opened image.
	dilated = imgs[7]	# Dilated image.
	combined = imgs[8]	# Combined image (re-inverted).
	contours = imgs[9]	# Contours of white areas.
	final = imgs[10]	# Final image.
	
	# TODO: Enable creating these based on input instead.
	kernel3x3 = create_kernel(w=3, h=3)
	kernel2x2 = create_kernel(w=2, h=2)
	kernel5x1 = create_kernel(w=5, h=1)

	x_start = 20

	img.caption(caption, left=(img.width - 250) / 2, top=5, width=250, height=100, font=font_title)

	if description:
		desc_font = Font(path="%s/source-code-pro/SourceCodePro-Medium.otf" % args.fonts, size=24)
		text_width = (desc_font.size) * int(len(description) * 0.7)
		img.caption(description, left=(img.width - text_width) / 2, top=80, width=text_width, height=100, font=desc_font)

	height = 120

	# Original.
	img.composite(orgimg, left=mpos(orgimg.width), top=height) 
	height += orgimg.height + gap
	
	# Detected head + cropped region of interest.
	head_row = create_row([detected, croproi], [0, 0], horizontal_gap, caption="Detected head  Cropped ROI")
	img.composite(head_row, left=mpos(head_row.width), top=height)
	height += head_row.height + gap

	# TODO: simplify the code below by making the symbols into images before they're used to create the rows.

	# Combine the threshold images.
	thr_row = create_row([globalthr, "+", adpthr, "=", combthr],
						[x_start,
						(4 * horizontal_gap, -15, 14 * horizontal_gap, font),
						0,
						(2 * horizontal_gap, -15, 8 * horizontal_gap, font),
						2 * horizontal_gap],
						horizontal_gap, fixed_width=img.width,
						caption="Global Threshold           Adaptive Threshold       Combined Threshold",
						caption_offset=(x_start, 0))
	img.composite(thr_row, left=mpos(thr_row.width), top=height)
	height += thr_row.height + gap

	# Open the combined threshold.
	open_row = create_row([combthr, u"∘", kernel2x2, "=", opened],
						[x_start,
						(5 * horizontal_gap, -5, 14 * horizontal_gap, font_math),
						0,
						(21 * horizontal_gap, -15, 10 * horizontal_gap, font),
						19 * horizontal_gap + 3],
						horizontal_gap, fixed_width=img.width,
						caption="Combined Threshold         2x2 Kernel               Opened Image",
						caption_offset=(x_start, 0))
	img.composite(open_row, left=mpos(open_row.width), top=height)
	height += open_row.height + gap

	# Dilate opened and combined threshold with a kernel3x3.
	dilated_row = create_row([opened, u"⊕", kernel3x3, "=", dilated],
						[x_start,
						(3 * horizontal_gap, -5, 14 * horizontal_gap, font_math),
						0,
						(17 * horizontal_gap, -15, 10 * horizontal_gap, font),
						15 * horizontal_gap + 3],
						horizontal_gap, fixed_width=img.width,
						caption="Opened Image               3x3 Kernel               Dilated Image",
						caption_offset=(x_start, 0))
	img.composite(dilated_row, left=mpos(dilated_row.width), top=height)
	height += dilated_row.height + gap

	# Inverted image and contour.
	contour_row = create_row([combined, contours], [0, 0], horizontal_gap, caption="  Re-Inverted         Contours")
	img.composite(contour_row, left=mpos(contour_row.width), top=height)
	height += contour_row.height + 2 * gap

	# Final.
	img.composite(final, left=mpos(final.width), top=height)
	height += final.height + gap

	return img
    # Easier to work in blob format
    blob = img.make_blob('pdf')
    pdf = Image(blob=blob)
    
    pages = len(pdf.sequence)
    print "Pages =", pages
    
    image = Image(
        width=pdf.width,
        height=pdf.height * pages
    )
    
    for i in xrange(pages):
        image.composite(
            img.sequence[i],
            top=pdf.height * i,
            left=0
        
        )
    
    img.make_blob('jpeg')


def convert_pdf_to_jpeg(blob):
    '''From stack overflow'''
    
    pdf = Image(blob=blob)
    pages = len(pdf.sequence)
    
    print pages

    image = Image(
예제 #59
0
        pages = len(imageFromPdf.sequence)
        print(pages)

        pages = 1
        
        image = Image(
            width = imageFromPdf.width,
            height = imageFromPdf.height*pages          
           
        )
        
        for i in range(pages):
            image.composite(
                imageFromPdf.sequence[i],
                top = imageFromPdf.height * i,
                left = 0
            )
            
        image.resize(250,250)
        image.alpha_channel = False
        image.format = 'png'
        print(image.size)
        image.background_color = Color('pink')
        
        image.type = 'grayscale'
        image.caption = file.split('.')[0]
        image.save(filename = fileDirectory+file.split('.')[0]+".png")

        image.clear()
        image.close()