当前位置: 首页>>代码示例>>Python>>正文


Python Image.composite方法代码示例

本文整理汇总了Python中wand.image.Image.composite方法的典型用法代码示例。如果您正苦于以下问题:Python Image.composite方法的具体用法?Python Image.composite怎么用?Python Image.composite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在wand.image.Image的用法示例。


在下文中一共展示了Image.composite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: convert_pdf_to_img

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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)
开发者ID:giussepi,项目名称:django-generic-utils,代码行数:37,代码来源:functions.py

示例2: pdf_to_text

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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"
开发者ID:tadamhicks,项目名称:pdf_to_text,代码行数:31,代码来源:wanding.py

示例3: generate_sprite

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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
开发者ID:dafiti,项目名称:ImageProcessing,代码行数:32,代码来源:images.py

示例4: resizeCanvas

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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
开发者ID:4Enjoy,项目名称:ADLib,代码行数:14,代码来源:BMFont.py

示例5: compose

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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()
开发者ID:ikol,项目名称:PURIKURA,代码行数:54,代码来源:composer.py

示例6: combine_layers

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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()
开发者ID:cedrikv,项目名称:static_map_generator,代码行数:15,代码来源:utils.py

示例7: overlay_that

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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
开发者ID:steder,项目名称:giraffe,代码行数:53,代码来源:giraffe.py

示例8: genTextPNG

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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
开发者ID:natet,项目名称:vb_textblaster,代码行数:17,代码来源:lib.py

示例9: create_thumbnail

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
 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()
开发者ID:magnusbraaten,项目名称:tassen,代码行数:17,代码来源:models.py

示例10: error_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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
开发者ID:universitas,项目名称:tassen,代码行数:18,代码来源:models.py

示例11: _save_page_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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
开发者ID:akash0675,项目名称:yapot,代码行数:49,代码来源:yapot.py

示例12: make_layer

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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
开发者ID:zastre,项目名称:sandboxattempt,代码行数:45,代码来源:render.py

示例13: set_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
    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()
开发者ID:iandennismiller,项目名称:gthnk,代码行数:21,代码来源:page.py

示例14: pdf_to_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
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
开发者ID:universitas,项目名称:tassen,代码行数:44,代码来源:models.py

示例15: process

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import composite [as 别名]
	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)
开发者ID:silverozzo,项目名称:vogo,代码行数:43,代码来源:tabl_maker.py


注:本文中的wand.image.Image.composite方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。