def populate_coordinate(table):
    try:
        i = Image(
            filename=
            f"{pdf_files_folder.joinpath(f'{table.fileId}.pdf').resolve()}[{table.page - 1}]"
        )
        pdf_width = i.width
        pdf_height = i.height
        i.close()

        x1 = int(table.x1 * pdf_width / table.pageWidth)
        x2 = int(table.x2 * pdf_width / table.pageWidth)
        y1 = int(table.y1 * pdf_height / table.pageHeight)
        y2 = int(table.y2 * pdf_height / table.pageHeight)

        connection = create_engine(
            f"mysql+mysqldb://{user}:{password}@{host}/{database}")
        query = f"UPDATE extraction_app.pdf_tables SET pdfWidth={pdf_width}, pdfHeight={pdf_height}, pdfX1={x1}," \
                f" pdfX2={x2}, pdfY1={y1}, pdfY2={y2} WHERE (uuid='{table.uuid}');"
        connection.execute(query)
        print(f"Populated coordinates for table ID {table.uuid}")
    except Exception as e:
        print(f"==== Error for ID {table.uuid}  ======")
        print(e)
        print(f"======================================")
예제 #2
0
    def converter(self):
        if not os.path.exists(self.path):
            os.mkdir(self.path)

        numero_de_paginas = len(self.arquivo.sequence)
        self.detalhes.append("Iniciando importação ...")

        try:
            for pagina in range(numero_de_paginas):
                nome_arquivo = "%s[%d]" % (self.arquivo_pdf, pagina)
                img = Image(filename=nome_arquivo, resolution=150)
                img.compression_quality = 99
                nome_arquivo = "pagina%d.jpg" % (pagina + 1)
                self.detalhes.append("\tPágina %d importada" % (pagina + 1))
                img.save(filename=self.path + nome_arquivo)
                self.lista_de_imagens.append(nome_arquivo)
                img.close()

            self.detalhes.append("Importação concluída.\n")
            time.sleep(1)
            self.arquivo.close()

        except BlobError:
            self.detalhes.append("Erro na importação!!!")
            time.sleep(1)
            self.detalhes.append("Fim.")
            self.arquivo.close()
            os.rmdir(self.path)
예제 #3
0
    def process(self, descriptor: StreamDescriptor, context: dict):

        # Ensuring the wand package is installed.
        ensure_wand()
        # noinspection PyPackageRequirements
        from wand.image import Image as WandImage

        # Copy the original info
        # generating thumbnail and storing in buffer
        # noinspection PyTypeChecker
        img = WandImage(file=descriptor)

        if self.crop is None and (
                self.format is None or img.format == self.format) and (
                    (self.width is None or img.width == self.width) and
                    (self.height is None or img.height == self.height)):
            img.close()
            descriptor.prepare_to_read(backend='memory')
            return

        if 'length' in context:
            del context['length']

        # opening the original file
        output_buffer = io.BytesIO()
        with img:
            # Changing format if required.
            if self.format and img.format != self.format:
                img.format = self.format

            # Changing dimension if required.
            if self.width or self.height:
                width, height, _ = validate_width_height_ratio(
                    self.width, self.height, None)
                img.resize(
                    width(img.size) if callable(width) else width,
                    height(img.size) if callable(height) else height)

            # Cropping
            if self.crop:
                img.crop(
                    **{
                        key: int(
                            int(value[:-1]) / 100 *
                            (img.width if key in ('width', 'left',
                                                  'right') else img.height)
                        ) if key in ('left', 'top', 'right', 'bottom', 'width',
                                     'height') and '%' in value else value
                        for key, value in self.crop.items()
                    })

            img.save(file=output_buffer)

            context.update(content_type=img.mimetype,
                           width=img.width,
                           height=img.height,
                           extension=guess_extension(img.mimetype))

        output_buffer.seek(0)
        descriptor.replace(output_buffer, position=0, **context)
def check_integrity(file):
    logging.debug("[Validation module] - Starting image integrity check")

    try:
        image = ImageP.open(io.BytesIO(file.content))
        image.verify()
        image.close()
    except Exception as e:
        logging.warning(
            f"[Validation module] - CHECK: Image integrity (1) - FAILED: {e}")
        return False

    try:
        image = ImageP.open(io.BytesIO(file.content))
        image.transpose(ImageP.FLIP_LEFT_RIGHT)
        image.close()
    except Exception as e:
        logging.warning(
            f"[Validation module] - CHECK: Image integrity (2) - FAILED: {e}")
        return False

    try:
        image = ImageW(file=io.BytesIO(file.content))
        _ = image.flip
        image.close()
    except Exception as e:
        logging.warning(
            f"[Validation module] - CHECK: Image integrity (3) - FAILED: {e}")
        return False

    logging.debug("[Validation module] - CHECK: Image integrity - PASSED")
    return True
예제 #5
0
def liquid(update, context):
    filename = datetime.now().strftime("%d%m%y-%H%M%S%f")
    power = get_param(update, 60, -100, 100)
    if power is None:
        return
    try:
        extension = get_image(update, context, path, filename)
    except:
        update.message.reply_text("I can't get the image! :(")
        return
    power = (100 - (power / 1.3)) / 100
    update.message.chat.send_action(ChatAction.UPLOAD_PHOTO)
    with Image(filename=path + filename + extension) as original:
        w, h = original.size
        new = Image()
        for i in range(len(original.sequence)):
            with original.sequence[i] as frame:
                img = Image(image=frame)
            img.liquid_rescale(int(w * power), int(h * power), delta_x=1)
            img.resize(w, h)
            new.sequence.append(img)
            img.close()
        new.save(filename=path + filename + extension)
        if extension == ".mp4":
            filename = mp4_fix(path, filename)
        send_image(update, path, filename, extension)
        new.close()
        os.remove(path + filename + extension)
예제 #6
0
    def compose_image_slide(self, image_path=None, text=None, slide_id=1):

        image_display_size = (300, 190)

        key = '%s-%s-%03d' % (self.emission.uuid, self.content_object.uuid, slide_id)
        path = os.path.join(SLIDE_BASE_DIR, key + '.{}'.format(IMAGE_OUTPUT_FORMAT))
        url = SLIDE_BASE_URL + key + '.{}'.format(IMAGE_OUTPUT_FORMAT)

        overlay_image = Image(filename=image_path)

        with Drawing() as draw:

            size = overlay_image.size

            if size[0] > size[1]:
                orientation = 'landscape'
                scale = float(image_display_size[1]) / float(size[1])
            else:
                orientation = 'portrait'
                scale = float(image_display_size[1]) / float(size[0])

            overlay_image.resize(int(size[0] * scale), int(size[1] * scale))

            #size = overlay_image.size

            width = 190
            height = 190
            overlay_image.crop(10, 0, width=width, height=height)

            draw.composite('over', left=int(width / 2) - 20, top=10, width=width, height=height, image=overlay_image)

            # text settings
            draw.font = SLIDE_BASE_FONT
            draw.font_size = 14
            draw.text_interline_spacing = 8
            draw.fill_color = Color('white')
            draw.text_antialias = True

            # draw text
            if text:
                draw.text(220, 10, text)

            # compose image
            with Image(filename=SLIDE_BASE_IMAGE) as image:
                draw(image)

                if IMAGE_OUTPUT_FORMAT == 'jpg':
                    image.compression_quality = 62
                    image.format = 'jpeg'

                image.save(filename=path)
                image.save(filename=os.path.join(SLIDE_BASE_DIR, 'debug-{}.{}'.format(slide_id, IMAGE_OUTPUT_FORMAT)))

        try:
            overlay_image.close()
        except Exception as e:
            # TODO: use narrowed exception(s)
            log.warning('unable to close magick/wand overlay image - {}'.format(e))

        return url
예제 #7
0
def scale(imagePath, face):
  # cloneImg.save(filename='{0}-{1}.jpg'.format(imagePath, i))

  face_x, face_y, face_w, face_h = face

  with Image(filename=imagePath) as img:
    img_w = img.size[0]
    img_h = img.size[1]

    w_delta = ((img_w - face_w) / 2) / NUM_IMAGES
    h_delta = ((img_h - face_h) / 2) / NUM_IMAGES

    gifImg = Image()

    for i in range(NUM_IMAGES, -1, -1):
      with img.clone() as cloneImg:
        if i == 0:
          cloneImg.crop(face_x, face_y, width=face_w, height=face_h)
          cloneImg.transform(resize='%dx%d' % (img_w, img_h))
        else:
          left = max(0, face_x - i * w_delta)
          top = max(0, face_y - i * h_delta)
          right = min(img_w, face_x + face_w + i * w_delta)
          bottom = min(img_h, face_y + face_h + i * h_delta)

          cloneImg.crop(left, top, right, bottom)
          cloneImg.transform(resize='%dx%d' % (img_w, img_h))
        gifImg.sequence.append(cloneImg)

    for frame in gifImg.sequence:
      with frame:
        frame.delay = 20
    gifImg.save(filename='%s.gif' % imagePath)
    gifImg.close()
    return '%s.gif' % imagePath
예제 #8
0
def cube(image: Image):
    """Make a 3D cube out of the image."""
    def s(x):
        return int(x / 3)

    image.resize(s(1000), s(860))
    image.format = "png"
    image.alpha_channel = 'opaque'

    image1 = image
    image2 = Image(image1)

    out = Image(width=s(3000 - 450), height=s(860 - 100) * 3)
    out.format = "png"

    image1.shear(background=Color("none"), x=-30)
    image1.rotate(-30)
    out.composite(image1, left=s(500 - 250), top=s(0 - 230) + s(118))
    image1.close()

    image2.shear(background="rgba(0,0,0,0)", x=30)
    image2.rotate(-30)
    image3 = Image(image2)
    out.composite(image2, left=s(1000 - 250) - s(72), top=s(860 - 230))
    image2.close()

    image3.flip()
    out.composite(image3, left=s(0 - 250) + s(68), top=s(860 - 230))
    image3.close()

    out.crop(left=80, top=40, right=665, bottom=710)

    return out
예제 #9
0
def magick_check(filename, flip=True):
    # very useful for xcf, psd and aslo supports pdf
    img = ImageW(filename=filename)
    if flip:
        temp = img.flip
    else:
        temp = img.make_blob(format='bmp')
    img.close()
    return temp
예제 #10
0
파일: tasks.py 프로젝트: firstval/beanbot
def series_to_animated_gif(L, filepath):
    imgs = Image(filename=L[0])
    for i in L[1:]:
        im2 = Image(filename=i)
        imgs.sequence.append(im2)
        for i in imgs.sequence:
            i.delay = 25
    imgs.save(filename=filepath)
    imgs.close()
    print('saved animated.gif')
예제 #11
0
async def wand_to_bytes(img: Image):
    ret = BytesIO()
    img.save(ret)
    if img.format is not "png":
        with Image(blob=ret.getvalue()) as converted:
            converted.format = "png"
            converted.save(ret)
    img.close()
    ret.seek(0)

    return ret
예제 #12
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()
예제 #13
0
    def _img_check(self, tree_content):
        """ Change path and check/convert to latex supported image type.

        there is 2 steps : i) extract svg, ii) convert file non supported by
        LaTeX

        Parameters
        ----------
        tree_content : etree
            etree arising from cdata parsing.
        """
        # Step 1.
        # Remove embedded svg file (tikz) and convert to img
        for svg in tree_content.findall('.//picture/svg'):
            width = svg.attrib['width']
            filename_svg = os.path.join(self.figpath,
                                        self.name + str(self.svg_id) + '.svg')
            with open(filename_svg, 'w') as f:
                f.write(
                    etree.tostring(svg, encoding='utf8',
                                   pretty_print=True).decode('utf-8'))
            img_svg = etree.Element('img',
                                    attrib={
                                        'src': filename_svg,
                                        'width': width
                                    })
            svg.getparent().append(img_svg)
            svg.getparent().remove(svg)
            # increment svg_id
            self.svg_id += 1

            # <picture> is then parsed in html2tex

        # Step 2.
        # check that img file are supported by LaTeX
        for img in tree_content.findall('.//img'):
            src = img.attrib['src']
            # remove percent-encoding with urlib
            src = urllib.parse.unquote(src)
            path, filename = os.path.split(src)
            basename, ext = os.path.splitext(filename)
            # need to be converted
            if ext not in LATEX_EXT:
                im = Image(filename=os.path.join(self.figpath, filename))
                fileout = os.path.join(self.figpath, basename + LATEX_IMG_OUT)
                im.save(filename=fileout)
                im.close()
                src = fileout
            else:
                src = os.path.join(self.figpath, filename)
            # store new path/file
            img.attrib['src'] = src
예제 #14
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()
예제 #15
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()
예제 #16
0
class ImageHandler(BaseHandler):
    pil_formats = ['jpg', 'jpeg', 'png', 'eps']
    magick_formats = ['psd', 'ai']

    def __init__(self, filename, file_type):
        self.local_file = filename
        self.file_type = file_type
        try:
            if file_type not in self.magick_formats:
                self.im = PILImage.open(filename)
                if self.im.mode == 'P':
                    self.im = self.im.convert('RGBA')
                self.size = self.im.size
                self.format = self.im.format
                self.width = self.im.width
                self.height = self.im.height
            else:
                self.im = WandImage(filename=filename+'[0]')
                self.format = file_type
                self.size = self.im.size
                self.width = self.im.width
                self.height = self.im.height
        except Exception as e:
            print e

    def is_smaller(self):
        if self.file_type in self.magick_formats:
            return False
        size = self.size
        width = size[0]
        height = size[1]
        return (width < 200) and (height < 200)

    def get_metadata(self):
        with exiftool.ExifTool() as et:
            metadata = et.get_metadata(self.local_file)
        return metadata

    def thumbnail(self, thumb_filename):
        if self.file_type in self.magick_formats:
            self.im.transform(resize=thumbnail_size)
            self.im.save(filename=thumb_filename)
        else:
            self.im.thumbnail((200, 200), PILImage.ANTIALIAS)
            self.im.save(thumb_filename, 'JPEG')

    def close(self):
        if self.file_type not in self.magick_formats:
            self.im.close()
예제 #17
0
 def imageDepth(self, att):
     imgtypes = ['jpg', 'png', 'gif', 'eps', 'jpeg', 'tiff']
     result = ""
     if att[1] in imgtypes:
         try:
             img = self.decodeAtt(att)
         except:
             print("Image decode error")
             image = None
         try:
             image = Image(blob=img)
         except:
             print("Image Error")
         if image != None:
             result = str(image.depth)
             image.close()
     return result
예제 #18
0
 def imageSize(self, att):
     imgtypes = ['jpg', 'png', 'gif', 'eps', 'jpeg', 'tiff']
     result = ""
     if att[1] in imgtypes:
         try:
             img = self.decodeAtt(att)
         except:
             print("Image decode error")
             image = None
         try:
             image = Image(blob=img)
         except:
             print("Image Error")
         if image != None:
             size = image.width * image.height
             result = str(size)
             image.close()
     return result
예제 #19
0
    def fatiar(self):
        os.chdir(self.path)
        nova_lista = []
        pagina = 1
        self.detalhes.append("Fatiamento iniciado")
        time.sleep(1)

        if self.capa:
            nova_lista.append("page0.jpg")
            os.rename("pagina1.jpg", "page0.jpg")
            self.detalhes.append("\tCapa criada")
            del self.lista_de_imagens[0]

        try:
            for imagem in self.lista_de_imagens:
                img = Image(filename=imagem)
                meia_pagina = int(img.size[0] / 2)

                with img[0:meia_pagina, 0:img.size[1]] as fatia:
                    fatia.save(filename="page%d.jpg" % pagina)
                    nova_lista.append("page%d.jpg" % pagina)
                    self.detalhes.append("\tPágina %d criada" % (pagina))
                    pagina += 1

                with img[meia_pagina:img.size[0], 0:img.size[1]] as fatia:
                    fatia.save(filename="page%d.jpg" % pagina)
                    nova_lista.append("page%d.jpg" % pagina)
                    self.detalhes.append("\tPágina %d criada" % (pagina))
                    pagina += 1

                img.close()
                os.remove(imagem)

        except BlobError:
            self.detalhes.append("Erro na importação !!!")
            time.sleep(1)
            self.detalhes.append("Fim.")
            img.close()
            os.rmdir(self.path)

        self.detalhes.append("Fatiamento concluído.\n")
        time.sleep(1)

        self.lista_de_imagens = nova_lista
예제 #20
0
def main():
    args = parseArguments()

    px = args.pixels
    out = args.out
    filename_out = os.path.splitext(ntpath.basename(args.input))[0] + ".png"

    img = Image(filename=args.input, resolution=(72, 72))
    img.clone().convert('png').save(filename="xxx.png")
    if args.mode is 'android' or args.mode is 'all':
        convertImage(img, px,       join(out, "drawable-mdpi"), filename_out)
        convertImage(img, int(px * 1.5), join(out, "drawable-hdpi"), filename_out)
        convertImage(img, px * 2,   join(out, "drawable-xhdpi"), filename_out)
        convertImage(img, px * 3,   join(out, "drawable-xxhdpi"), filename_out)
        convertImage(img, px * 4,   join(out, "drawable-xxxhdpi"), filename_out)
    elif args.mode is 'ios' or args.mode is 'all':
        convertImage(img, px * 2,   join(out, "ios-2x"), filename_out)
        convertImage(img, px,       join(out, "ios-1x"), filename_out)
        convertImage(img, px * 3,   join(out, "ios-3x"), filename_out)
    img.close()
예제 #21
0
def tile(seq, ofilename):
    refImage = Image(
        filename=os.path.join(seq.path, seq.printpatt.format(seq.first)))
    rx = refImage.width
    ry = refImage.height
    count = seq.last - seq.first + 1
    (bx, x), (by, y) = block(rx, ry, count)
    refImage.close()

    imgContainer = Image(width=x, height=y)
    for i in range(seq.first, seq.last + 1):
        filename = os.path.join(seq.path, seq.printpatt.format(i))
        with Image(filename=filename) as tile:
            cx, cy = indx(bx, by, i)
            left = cx * rx
            top = cy * ry
            imgContainer.composite(image=tile, left=left, top=top)
    imgContainer.save(filename=ofilename)
    imgContainer.close()

    return bx, by, count
예제 #22
0
def kekify(kek_param, filename, extension, file):
    if kek_param == "-m":
        result = multikek(filename, extension)
        return None, None, result
    if file == None:
        source = Image(filename=path + filename + extension)
    else:
        source = file
    w = source.width
    h = source.height
    c, p1, p2, f = get_values(kek_param, w, h)
    with source.clone() as part1:
        part1.crop(c[0], c[1], c[2], c[3])
        with part1.clone() as part2:
            getattr(part2, f)()
            new_canvas = Image()
            new_canvas.blank(w, h)
            new_canvas.composite(part1, p1[0], p1[1])
            new_canvas.composite(part2, p2[0], p2[1])
    source.close()
    return w, h, new_canvas
예제 #23
0
def orient_and_resize(image_filename):
    resized_images = {}
    
    img = Image(filename=image_filename)
    img.auto_orient()

    (w,h) = img.size
    w = int(w)
    h = int(h)

    filename_base = image_filename
    filename_base = filename_base.replace("/", "-")
    filename_base = filename_base.replace(" ", "_")

    with img.clone() as img_clone:
        img_clone.resize(1280, int((1280.0/w)*h))
        fname = "Resized/" + filename_base + "_1280.jpg"
        resized_images['1280'] = fname
        img_clone.save(filename=PREFIX_DIR + fname)

    with img.clone() as img_clone:
        img_clone.resize(640, int((640.0/w)*h))
        fname = "Resized/" + filename_base + "_640.jpg"
        resized_images['640'] = fname
        img_clone.save(filename=PREFIX_DIR + fname)

    with img.clone() as img_clone:
        img_clone.resize(320, int((320.0/w)*h))
        fname = "Resized/" + filename_base + "_320.jpg"
        resized_images['320'] = fname
        img_clone.save(filename=PREFIX_DIR + fname)

    with img.clone() as img_clone:
        img_clone.resize(160, int((160.0/w)*h))
        fname = "Resized/" + filename_base + "_160.jpg"
        resized_images['160'] = fname
        img_clone.save(filename=PREFIX_DIR + fname)

    img.close()
    return ((w, h), resized_images)
예제 #24
0
def project_files(filenames, projection_type, outfile):
    '''Project over multiple files'''
    # Prepare intensity projection output.
    projection = Image(filename=filenames.pop(0))
    if projection_type == 'max_intesity':
        perform_projection = lighten
    else:
        perform_projection = darken

    # Loop over list of files projecting them on previously predefined background.
    for img_filename in filenames:
        # print >> sys.stderr, 'Projecting ' + img_filename
        with Image(filename=img_filename) as img:
            if img.type != 'grayscale':
                img.type = 'grayscale'
            assert projection.size == img.size
            perform_projection(projection, img)

    # Save intensity projection as PNG.
    with projection.convert('png') as converted:
        converted.save(file=outfile)
    projection.close()
예제 #25
0
def pdfToImage(f_path, pdf_list):
    """
    Esta función es útil para convertir PDF escaneados en imánes en formato PNG.
    Se generan tantas imagenes como páginas tenga el PDF a convertir.
    
    Parámetros:
    
    f_path = path de la carpeta donde guardar las imágenes.
    pdf_list = lista de PDF escaneados.
    """

    image_folder = f_path + 'Images/'

    if not os.path.isdir(image_folder):
        os.mkdir(image_folder)

    name = []
    for pdf in pdf_list:
        name.append(pdf.replace('.', '/').split('/')[-2])

    for i in range(0, len(pdf_list)):

        try:
            opdf = Image(filename=pdf_list[i], resolution=300)
            ipdf = opdf.convert('png')

            for idx, img in enumerate(ipdf.sequence):
                page = Image(image=img)
                page.save(filename=image_folder + name[i] + '_' + 'image' +
                          str(idx) + '.png')
                page.destroy()

            #print('Procesado ->', pdf_list[i])
            ipdf.destroy()
            opdf.close()

        except:
            #print('No procesado ->', pdf_list[i])
            pass
예제 #26
0
    def make_thumbnail(self):
        """ Generate thumbnail """
        image = Image(file=self.image)
        image.resize(220, 220)

        thumb_name, thumb_extension = str(self.image).split('/')[-1].split('.')

        thumb_filename = thumb_name + '_thumb.' + thumb_extension

        # Save thumbnail to in-memory file as StringIO
        temp_thumb = BytesIO()
        image.save(file=temp_thumb)
        temp_thumb.seek(0)

        # set save=False, otherwise it will run in an infinite loop
        self.thumbnail.save(thumb_filename,
                            ContentFile(temp_thumb.read()),
                            save=False)
        temp_thumb.close()
        image.close()

        return True
예제 #27
0
def create_image(path, width, height):
    image = Image(filename=path)
    if (image.width >= width or image.height >= height):
        # breite ist maßgebend
        h = height
        w = width
        if (image.width / width < image.height / height):
            h = int(round(image.height / (image.width / width)))
        # höhe ist maßgebend
        else:
            w = int(round(image.width / (image.height / height)))

        image.resize(w, h)
        image.crop(width=width, height=height, gravity='center')
        return image
    else:
        outerImg = Image(width=width, height=height, background=image[1][1])
        outerImg.format = image.format.lower()
        outerImg.composite(image,
                           left=int((width - image.width) / 2),
                           top=int((height - image.height) / 2))
        image.close()
        return outerImg
예제 #28
0
파일: pdf.py 프로젝트: zxytim/jrp
def pdf_data_to_thumbnails_by_imagemagick(pdf_data):
    """This is quite buggy.
    :return: dict: index -> png_data
    """
    if pdf_data is None:
        return {0: None}

    rst = {}
    tmpdir = tempfile.mkdtemp(prefix='mymagick')
    try:
        os.environ['MAGICK_TMPDIR'] = tmpdir

        pdf_imgs = Image()
        pdf_imgs.read(blob=pdf_data)

        # XXX: There's a known bug that some pdf cannot be read using
        #       constructor, but to use `read` method after construction of
        #       Image. The following code will result in
        #       wand.exceptions.CorruptImageError:
        #               with Image(blob=pdf_data) as pdf_imgs:

        for idx, i in enumerate(pdf_imgs.sequence[:config.NUM_THUMBNAIL_PAGE]):
            j = Image()
            j.read(image=i)
            j.format = "jpg"
            j.transform(resize="x{}".format(config.PDF_THUMBNAIL_SIZE))

            bio = io.BytesIO()
            j.save(bio)
            img_data = bio.getvalue()

            rst[idx] = img_data
        pdf_imgs.close()
    finally:
        shutil.rmtree(tmpdir)

    return rst
예제 #29
0
def pdf_data_to_thumbnails_by_imagemagick(pdf_data: bytes, pages: List[int],
                                          width_max: int, height_max: int):
    """
    Convert pdf data to set of images using imagemagick (via wand).

    :return: dict: index -> png_data
    """
    rst = {}
    tmpdir = tempfile.mkdtemp(prefix="mymagick")
    try:
        os.environ["MAGICK_TMPDIR"] = tmpdir

        pdf_imgs = Image()
        pdf_imgs.read(blob=pdf_data)

        # XXX: There's a known bug that some pdf cannot be read using
        #       constructor, but to use `read` method after construction of
        #       Image. The following code will result in
        #       wand.exceptions.CorruptImageError:
        #               with Image(blob=pdf_data) as pdf_imgs:

        for idx in pages:
            blob = pdf_imgs.sequence[idx]
            j = Image(blob)
            j.format = "jpg"
            j.transform(resize="{}x{}".format(width_max, height_max))

            bio = io.BytesIO()
            j.save(bio)
            img_data = bio.getvalue()

            rst[idx] = img_data
        pdf_imgs.close()
    finally:
        shutil.rmtree(tmpdir)

    return rst
예제 #30
0
    def do_cube(img):
        with WandImage(blob=img) as image:

            def s(x):
                return int(x / 3)

            image.resize(s(1000), s(860))
            image.format = "png"
            image.alpha_channel = 'opaque'

            image1 = image
            image2 = WandImage(image1)

            out = WandImage(width=s(3000 - 450), height=s(860 - 100) * 3)
            out.format = "png"

            image1.shear(background=wand.color.Color("none"), x=-30)
            image1.rotate(-30)
            out.composite(image1, left=s(500 - 250), top=s(0 - 230) + s(118))
            image1.close()

            image2.shear(background=wand.color.Color("rgba(0,0,0,0)"), x=30)
            image2.rotate(-30)
            image3 = WandImage(image2)
            out.composite(image2, left=s(1000 - 250) - s(72), top=s(860 - 230))
            image2.close()

            image3.flip()
            out.composite(image3, left=s(0 - 250) + s(68), top=s(860 - 230))
            image3.close()

            out.crop(left=80, top=40, right=665, bottom=710)

            buffer = BytesIO()
            out.save(buffer)
            buffer.seek(0)
            return buffer
예제 #31
0
 def opImplement(self):
     self.takeScreenShort();
     try:
         from wand.image import Image
         from wand.color import Color
         gifSeq = Image();
         index=0;
         
         for index,file in enumerate(self.seq):
             with Image(filename=file) as seq:
                 gifSeq.sequence.append(seq);
                 #We add something in s/100 secound.
                 gifSeq.sequence[index].delay = self.delay;
                 #After changing delay that must be call this function
                 gifSeq.sequence[index].destroy();
         gifSeq.save(filename=self.gif);
         gifSeq.close();
     except:
         raise;
     finally:
         import os;
         for file in self.seq:
             os.remove(file);
     return self.data;
예제 #32
0
def fap(update, context):
    filename = datetime.now().strftime("%d%m%y-%H%M%S%f")
    try:
        extension = get_image(update, context, path, filename)
    except:
        update.message.reply_text("I can't get the image! :(")
        return
    update.message.chat.send_action(ChatAction.UPLOAD_PHOTO)

    with Image(filename=path + filename + extension) as decal:
        decal.resize(320, 172)
        w, h = decal.size
        decal.virtual_pixel = 'transparent'
        source_points = ((0, 0), (w, 0), (w, h), (0, h))
        with Image(filename=launchpad_gif) as template_gif:
            new = Image()
            for i in range(len(template_gif.sequence)):
                with template_gif.sequence[i] as frame:
                    img = Image(image=frame)
                    img.delay = 6
                destination_points = (coords_by_frame[i])
                order = chain.from_iterable(
                    zip(source_points, destination_points))
                arguments = list(chain.from_iterable(order))
                decal_current = Image(image=decal)
                decal_current.matte_color = "rgba(255, 255, 255, 0)"
                decal_current.distort('perspective', arguments)
                img.composite(decal_current, left=0, top=0)
                new.sequence.append(img)
                decal_current.close()
                img.close()
            new.save(filename=path + "result.mp4")
            result_filename = mp4_fix(path, "result")
            send_image(update, path, result_filename, ".mp4")
            new.close()
            os.remove(path + result_filename + ".mp4")
            os.remove(path + filename + extension)
예제 #33
0
    def compose_main_slide(self, primary_text=None, secondary_text=None, overlay_image_path=None, slide_id=0):

        if overlay_image_path and os.path.isfile(overlay_image_path):
            key = '%s-%s-%03d' % (self.emission.uuid, self.content_object.uuid, slide_id)
            path = os.path.join(SLIDE_BASE_DIR, key + '.{}'.format(IMAGE_OUTPUT_FORMAT))
            url = SLIDE_BASE_URL + key + '.{}'.format(IMAGE_OUTPUT_FORMAT)
        else:
            # TODO: not used anymore
            overlay_image_path = SLIDE_DEFAULT_IMAGE
            key = 'default'
            path = os.path.join(SLIDE_BASE_DIR, key + '.png')
            url = SLIDE_BASE_URL + key + '.png'


        overlay_image = Image(filename=overlay_image_path)

        with Drawing() as draw:

            # add overlay image
            draw.composite('over', left=210, top=10, width=100, height=100, image=overlay_image)

            # text settings
            # draw.font = SLIDE_BASE_FONT
            # draw.font_size = 14
            # draw.text_interline_spacing = 8
            # draw.fill_color = Color('white')
            # draw.text_antialias = True

            # text settings
            draw.font = SLIDE_BASE_FONT
            draw.font_size = 14
            draw.text_interline_spacing = 8
            draw.fill_color = Color('white')
            draw.text_antialias = True

            # draw text
            if primary_text:
                draw.text(10, 28, primary_text)

            if secondary_text:
                draw.font_size = 13
                draw.text_interline_spacing = 5
                draw.text(10, 140, secondary_text)

            # compose image
            with Image(filename=SLIDE_BASE_IMAGE) as image:
                draw(image)

                if IMAGE_OUTPUT_FORMAT == 'jpg':
                    image.compression_quality = 70
                    image.format = 'jpeg'

                image.save(filename=path)
                image.save(filename=os.path.join(SLIDE_BASE_DIR, 'debug-{}.{}'.format(slide_id, IMAGE_OUTPUT_FORMAT)))

        try:
            overlay_image.close()
        except Exception as e:
            # TODO: use narrowed exception(s)
            log.warning('unable to close magick/wand overlay image - {}'.format(e))


        return url
예제 #34
0
def main():
	args = get_args()

	draw = Drawing()
	draw.font = args.font_file
	draw.font_size = args.font_size

	font_name = args.font_name
	out_dir = args.out_dir

	img_ref = Image(width=1000, height=1000)

	if args.verbose:
		print "Writing " + out_dir + "/" + font_name + ".c"
	f = open(out_dir + "/" + font_name + ".c", 'wb+')
	write_comment(f)
	f.write("#include \"font.h\"\n\n")

	font_height = 0
	range_first = 0x20
	range_last = 0x7d
	font_width = []
	max_width = 0
	for x in range(range_first, range_last + 1):
		letter = chr(x)
		metrics = draw.get_font_metrics(img_ref, letter)
		text_height = int(round(metrics.text_height + 2))
		if font_height == 0:
			font_height = text_height
		assert (font_height == text_height), "font height changed!"
		if max_width == 0:
			max_width = metrics.maximum_horizontal_advance + 2
		assert (max_width == metrics.maximum_horizontal_advance + 2), \
			"font advance width changed!"
		text_width = int(round(metrics.text_width + 2))
		font_width.append(text_width)
		img = Image(width=text_width, height=text_height)
		d = draw.clone()
		d.text(0, int(metrics.ascender), letter)
		d(img)

		img.depth = 1;

		f.write("static const unsigned char ")
		f.write("letter_" + str(hex(x)[2:]) + "[] = {\n")
		c_hex_print(f, img.make_blob(format='A'))
		f.write("};\n\n")
		img.close()

	f.write("static const struct font_letter letters[] = {\n")
	for x in range(range_first, range_last + 1):
		letter_var_name = "letter_" + str(hex(x)[2:])
		f.write("\t{ " + letter_var_name + ", ")
		f.write("sizeof(" + letter_var_name + "), ")
		f.write(str(font_width[x - range_first]) + "},\n")
	f.write("};\n\n")

	f.write("const struct font font_" + font_name + " = {\n")
	f.write("\t.first = " + str(hex(range_first)) + ",\n")
	f.write("\t.last = " + str(hex(range_last)) + ",\n")
	f.write("\t.letters = letters,\n")
	f.write("\t.height = " + str(font_height) + ",\n")
	f.write("\t.max_width = " + str(max_width) + ",\n")
	f.write("};\n")
	f.close()

	if args.verbose:
		print "Writing " + out_dir + "/" + font_name + ".h"
	f = open(out_dir + "/" + font_name + ".h", 'wb+')
	write_comment(f)
	f.write("#ifndef __" + font_name.upper() + "_H\n");
	f.write("#define __" + font_name.upper() + "_H\n");
	f.write("#include \"font.h\"\n")
	f.write("extern const struct font font_" + font_name + ";\n")
	f.write("#endif /*__" + font_name.upper() + "_H*/\n");
	f.close()
예제 #35
0
        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()

        #display(image)
예제 #36
0
    def compose_main_slide(self,
                           primary_text=None,
                           secondary_text=None,
                           overlay_image_path=None,
                           slide_id=0):

        if overlay_image_path and os.path.isfile(overlay_image_path):
            key = '%s-%s-%03d' % (self.emission.uuid, self.content_object.uuid,
                                  slide_id)
            path = os.path.join(SLIDE_BASE_DIR,
                                key + '.{}'.format(IMAGE_OUTPUT_FORMAT))
            url = SLIDE_BASE_URL + key + '.{}'.format(IMAGE_OUTPUT_FORMAT)
        else:
            # TODO: not used anymore
            overlay_image_path = SLIDE_DEFAULT_IMAGE
            key = 'default'
            path = os.path.join(SLIDE_BASE_DIR, key + '.png')
            url = SLIDE_BASE_URL + key + '.png'

        overlay_image = Image(filename=overlay_image_path)

        with Drawing() as draw:

            # add overlay image
            draw.composite('over',
                           left=210,
                           top=10,
                           width=100,
                           height=100,
                           image=overlay_image)

            # text settings
            # draw.font = SLIDE_BASE_FONT
            # draw.font_size = 14
            # draw.text_interline_spacing = 8
            # draw.fill_color = Color('white')
            # draw.text_antialias = True

            # text settings
            draw.font = SLIDE_BASE_FONT
            draw.font_size = 14
            draw.text_interline_spacing = 8
            draw.fill_color = Color('white')
            draw.text_antialias = True

            # draw text
            if primary_text:
                draw.text(10, 28, primary_text)

            if secondary_text:
                draw.font_size = 13
                draw.text_interline_spacing = 5
                draw.text(10, 140, secondary_text)

            # compose image
            with Image(filename=SLIDE_BASE_IMAGE) as image:
                draw(image)

                if IMAGE_OUTPUT_FORMAT == 'jpg':
                    image.compression_quality = 70
                    image.format = 'jpeg'

                image.save(filename=path)
                image.save(filename=os.path.join(
                    SLIDE_BASE_DIR, 'debug-{}.{}'.format(
                        slide_id, IMAGE_OUTPUT_FORMAT)))

        try:
            overlay_image.close()
        except Exception as e:
            # TODO: use narrowed exception(s)
            log.warning(
                'unable to close magick/wand overlay image - {}'.format(e))

        return url
예제 #37
0
파일: akari.py 프로젝트: wodim/akari
    def compose(self, image):
        utils.logger.info('Starting to compose Akari...')

        if 'akari:frames' not in cache:
            # cache miss
            utils.logger.warning('Akari frames were not warmed up!')
            self.warmup()

        akari_frames = cache.get('akari:frames')
        self.width = cache.get('akari:width')
        self.height = cache.get('akari:height')

        if self.type == 'animation' and len(akari_frames) < 2:
            # if we were asked to generate an animation but there's only one
            # mask, then we're generating a still image
            self.type = 'still'
        elif self.type == 'still' and len(akari_frames) > 1:
            # if we were asked to generate a still image and there are several
            # masks, use only the first one
            akari_frames = [akari_frames[0]]

        # now, get the background image
        filename = image.filename
        with Image(filename=filename) as original:
            # if it's an animation, take only the first frame
            if original.animation:
                bg_img = Image(original.sequence[0])
            else:
                bg_img = Image(original)
        # remove the alpha channel, if any
        bg_img.alpha_channel = False
        # resize it
        bg_img.transform(resize='{}x{}^'.format(self.width, self.height))
        bg_img.crop(width=self.width, height=self.height, gravity='center')

        if self.text:
            # generate the drawing to be applied to each frame
            if self.caption_type == 'seinfeld':
                caption, drawing = self._caption_seinfeld()
            elif self.caption_type == 'sanandreas':
                caption, drawing = self._caption_sanandreas()
            else:
                caption, drawing = self._caption_akari()
        else:
            caption, drawing = '', None

        result = Image()  # this will be the resulting image
        for akari_frame in akari_frames:
            # take the background image
            this_frame = Image(bg_img)

            # put akari on top of it
            this_frame.composite(akari_frame, left=0, top=0)

            if drawing:
                # draw the caption on this frame
                drawing(this_frame)

            if len(akari_frames) == 1:
                # we are done already
                result = Image(this_frame)
            else:
                # add the frame to the result image
                result.sequence.append(this_frame)
                with result.sequence[-1]:
                    result.sequence[-1].delay = 10
            # remove this frame from memory (it's in the sequence already)
            this_frame.close()
        if not akari_frames:
            # shortcut in case there's no mask
            this_frame = Image(bg_img)
            if drawing:
                drawing(this_frame)
            result = Image(this_frame)
            this_frame.close()

        # save the result
        filename = image.get_path(self.type)
        result.compression_quality = 100
        result.save(filename=filename)

        # destroy everything
        if drawing:
            drawing.destroy()
        for frame in result.sequence:
            frame.destroy()
        result.close()
        bg_img.close()

        try:
            # if the gif is too big, it has to be discarded. a new one
            # will be generated using a different image this time.
            if os.path.getsize(filename) > 3072 * 1024:
                raise AkariTooBigError('Composed an animation that is too big')
        except FileNotFoundError:
            # sometimes Wand fails to save the animation, and does not even
            # raise an exception. retry in this case.
            raise AkariWandIsRetardedError('Wand failed to save the animation')

        utils.logger.info('Akari composed and saved as "%s"', filename)
        self.filename = filename
        self.caption = caption
예제 #38
0
def main():
    args = get_args()

    draw = Drawing()
    draw.font = args.font_file
    draw.font_size = args.font_size

    font_name = args.font_name
    out_dir = args.out_dir

    img_ref = Image(width=1000, height=1000)

    if args.verbose:
        print "Writing " + out_dir + "/" + font_name + ".c"
    f = open(out_dir + "/" + font_name + ".c", 'wb+')
    write_comment(f)
    f.write("#include \"font.h\"\n\n")

    font_height = 0
    range_first = 0x20
    range_last = 0x7d
    font_width = []
    max_width = 0
    for x in range(range_first, range_last + 1):
        letter = chr(x)
        metrics = draw.get_font_metrics(img_ref, letter)
        text_height = int(round(metrics.text_height + 2))
        if font_height == 0:
            font_height = text_height
        assert (font_height == text_height), "font height changed!"
        if max_width == 0:
            max_width = metrics.maximum_horizontal_advance + 2
        assert (max_width == metrics.maximum_horizontal_advance + 2), \
         "font advance width changed!"
        text_width = int(round(metrics.text_width + 2))
        font_width.append(text_width)
        img = Image(width=text_width, height=text_height)
        d = draw.clone()
        d.text(0, int(metrics.ascender), letter)
        d(img)

        img.depth = 1

        f.write("static const unsigned char ")
        f.write("letter_" + str(hex(x)[2:]) + "[] = {\n")
        c_hex_print(f, img.make_blob(format='A'))
        f.write("};\n\n")
        img.close()

    f.write("static const struct font_letter letters[] = {\n")
    for x in range(range_first, range_last + 1):
        letter_var_name = "letter_" + str(hex(x)[2:])
        f.write("\t{ " + letter_var_name + ", ")
        f.write("sizeof(" + letter_var_name + "), ")
        f.write(str(font_width[x - range_first]) + "},\n")
    f.write("};\n\n")

    f.write("const struct font font_" + font_name + " = {\n")
    f.write("\t.first = " + str(hex(range_first)) + ",\n")
    f.write("\t.last = " + str(hex(range_last)) + ",\n")
    f.write("\t.letters = letters,\n")
    f.write("\t.height = " + str(font_height) + ",\n")
    f.write("\t.max_width = " + str(max_width) + ",\n")
    f.write("};\n")
    f.close()

    if args.verbose:
        print "Writing " + out_dir + "/" + font_name + ".h"
    f = open(out_dir + "/" + font_name + ".h", 'wb+')
    write_comment(f)
    f.write("#ifndef __" + font_name.upper() + "_H\n")
    f.write("#define __" + font_name.upper() + "_H\n")
    f.write("#include \"font.h\"\n")
    f.write("extern const struct font font_" + font_name + ";\n")
    f.write("#endif /*__" + font_name.upper() + "_H*/\n")
    f.close()
예제 #39
0
    def compose_image_slide(self, image_path=None, text=None, slide_id=1):

        image_display_size = (300, 190)

        key = '%s-%s-%03d' % (self.emission.uuid, self.content_object.uuid,
                              slide_id)
        path = os.path.join(SLIDE_BASE_DIR,
                            key + '.{}'.format(IMAGE_OUTPUT_FORMAT))
        url = SLIDE_BASE_URL + key + '.{}'.format(IMAGE_OUTPUT_FORMAT)

        overlay_image = Image(filename=image_path)

        with Drawing() as draw:

            size = overlay_image.size

            if size[0] > size[1]:
                orientation = 'landscape'
                scale = float(image_display_size[1]) / float(size[1])
            else:
                orientation = 'portrait'
                scale = float(image_display_size[1]) / float(size[0])

            overlay_image.resize(int(size[0] * scale), int(size[1] * scale))

            #size = overlay_image.size

            width = 190
            height = 190
            overlay_image.crop(10, 0, width=width, height=height)

            draw.composite('over',
                           left=int(width / 2) - 20,
                           top=10,
                           width=width,
                           height=height,
                           image=overlay_image)

            # text settings
            draw.font = SLIDE_BASE_FONT
            draw.font_size = 14
            draw.text_interline_spacing = 8
            draw.fill_color = Color('white')
            draw.text_antialias = True

            # draw text
            if text:
                draw.text(220, 10, text)

            # compose image
            with Image(filename=SLIDE_BASE_IMAGE) as image:
                draw(image)

                if IMAGE_OUTPUT_FORMAT == 'jpg':
                    image.compression_quality = 62
                    image.format = 'jpeg'

                image.save(filename=path)
                image.save(filename=os.path.join(
                    SLIDE_BASE_DIR, 'debug-{}.{}'.format(
                        slide_id, IMAGE_OUTPUT_FORMAT)))

        try:
            overlay_image.close()
        except Exception as e:
            # TODO: use narrowed exception(s)
            log.warning(
                'unable to close magick/wand overlay image - {}'.format(e))

        return url