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


Python Image.crop方法代码示例

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


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

示例1: compose_image_slide

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

示例2: wand1

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
def wand1():
    """This is Python Wand example 1"""
    the_time = t.asctime()

    print "Importing image ", IFILE
    img_1 = Image(filename=IFILE)

    print "Cropping and resizing the image"
    img_1.crop(300, 0, width=300, height=282)
    img_1.resize(width=600, height=564)

    print "Creating a drawing and overlaying on it"
    draw = Drawing()

    draw.circle((100, 100), (120, 120))

    draw.rectangle(left=img_1.width-300, top=img_1.height-45, width=230,
               height=40, radius=5)

    draw.font_size = 17
    draw.fill_color = Color('white')
    draw.text_color = Color('white')
    draw.text(img_1.width-290, img_1.height-20, the_time)
    draw(img_1)

    print "Displaying, close the XTERM when done"
    display(img_1)
开发者ID:wadester,项目名称:wh_test_py,代码行数:29,代码来源:gr_wand1.py

示例3: convert_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
def convert_image(pngfile, pf, outdir=".",
                  resize=1000, format="jpeg", rotate=0,
                  rows=':', cols=':', labelrows=None, labelcols=None):
    resizefile = op.join(outdir, pf + ".resize.jpg")
    mainfile = op.join(outdir, pf + ".main.jpg")
    labelfile = op.join(outdir, pf + ".label.jpg")
    img = Image(filename=pngfile)
    exif = dict((k, v) for k, v in img.metadata.items() if k.startswith('exif:'))

    # Rotation, slicing and cropping of main image
    if rotate:
        img.rotate(rotate)
    if resize:
        w, h = img.size
        if min(w, h) > resize:
            if w < h:
                nw, nh = resize, resize * h / w
            else:
                nw, nh = resize * w / h, resize
            img.resize(nw, nh)
            logging.debug("Image `{0}` resized from {1}px:{2}px to {3}px:{4}px".\
                            format(pngfile, w, h, nw, nh))
    img.format = format
    img.save(filename=resizefile)

    rimg = img.clone()
    if rows != ':' or cols != ':':
        w, h = img.size
        ra, rb = slice(rows, h)
        ca, cb = slice(cols, w)
        # left, top, right, bottom
        logging.debug("Crop image to {0}:{1} {2}:{3}".format(ra, rb, ca, cb))
        img.crop(ca, ra, cb, rb)
        img.format = format
        img.save(filename=mainfile)
    else:
        mainfile = resizefile

    # Extract text labels from image
    if labelrows or labelcols:
        w, h = rimg.size
        if labelrows and not labelcols:
            labelcols = ':'
        if labelcols and not labelrows:
            labelrows = ':'
        ra, rb = slice(labelrows, h)
        ca, cb = slice(labelcols, w)
        logging.debug("Extract label from {0}:{1} {2}:{3}".format(ra, rb, ca, cb))
        rimg.crop(ca, ra, cb, rb)
        rimg.format = format
        rimg.save(filename=labelfile)
    else:
        labelfile = None

    return resizefile, mainfile, labelfile, exif
开发者ID:tanghaibao,项目名称:jcvi,代码行数:57,代码来源:grabseeds.py

示例4: animate_slice

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
def animate_slice(sliceviewer, name, start, end, filename, num_frames=10, font_size=24):
    """Generate an animated gif of a 2D slice moving through a third dimension.

    Args:
        sliceviewer (SliceViewer): A sliceviewer instance.
        name (str): The name of the third dimension to use.
        start (float): The starting value of the third dimension.
        end (float): The end value of the third dimension.
        filename (str): The file to save the gif to.

    Kwargs:
        num_frames (int): The number of frames the gif should contain.
        font_size: (int): The size of the caption.

    Example:
        ws = CreateMDWorkspace(3, Extents=[-10,10,-10,10,-10,10], Names=["X","Y","Z"], Units=["u","u","u"])
        FakeMDEventData(ws, PeakParams=[10000,0,0,0,1])
        sv = plotSlice(ws)
        #Resize and configure the slice viewer how you want the output to look
        sv.setNormalization(1) # We need to normalize by volume in this case, or the data won't show up
        #This will create a gif iterating from Z = -1 to Z = 1
        animate_slice(sv, "Z", -1, 1, "output.gif")
    """
    #Generate all the individual frames
    images = []
    for slice_point in numpy.linspace(start, end, num_frames):
        sliceviewer.setSlicePoint(name, slice_point)
        sliceviewer.refreshRebin()
        qimg = sliceviewer.getImage().toImage()
        data = QByteArray()
        buf = QBuffer(data)
        qimg.save(buf, "PNG")
        image = Image(blob=str(data))
        captionstrip_size = font_size + 10
        #To add whitespace to the top, we add a vertical border,
        #then crop out the bottom border
        image.border(Color("#fff"), 0, captionstrip_size)
        image.crop(0, 0, image.width, image.height - captionstrip_size)
        #Write the caption into the whitespace
        draw = Drawing()
        draw.font_size = font_size
        draw.text(5, font_size,"%s = %g" % (name,slice_point))
        draw(image)
        images.append(image)
    #Create a new image with the right dimensions
    animation = Image(width=images[0].width, height=images[0].height)
    #Copy in the frames from all the generated images
    for image in images:
        animation.sequence.append(image.sequence[0])
    #Drop the initial blank frame
    del animation.sequence[0]
    #Write the animation to disk
    animation.save(filename=filename)
开发者ID:rosswhitfield,项目名称:mantid,代码行数:55,代码来源:SliceViewAnimator.py

示例5: renderAnimation

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

示例6: magick_crop

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
 def magick_crop(self, image_url=None, dataX=0, dataY=0, dataWidth=0, dataHeight=0, dataRotate=0, dataScaleX=1, dataScaleY=1, **kw):
     if 'ir.attachment' in image_url:
         # binary -> decode -> wand.image -> imagemagick -> make_blob() -> encode -> binary
         img_attachment = request.env['ir.attachment'].browse(int(image_url.split('/')[4].split('_')[0]))
         wand_img = Image(blob=getattr(img_attachment, 'datas').decode('base64'))
         try:
             wand_img.crop(int(dataX), int(dataY), width=int(dataWidth), height=int(dataHeight))
             if dataScaleX and dataScaleY:
                 wand_img.resize(int(wand_img.width * float(dataScaleX)), int(wand_img.height * float(dataScaleY)))
             if dataRotate:
                 wand_img.rotate(int(dataRotate))
             img_attachment.write({ 'datas': wand_img.make_blob().encode('base64') })
         except Exception as e:
             return ': '.join(e)
         return 'Magic Crop Completed!'
     else:
         return 'Please using attachment as image!'
开发者ID:vertelab,项目名称:odoo-imagemagick,代码行数:19,代码来源:imagemagick_cropper.py

示例7: open_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
def open_image(path, colors, width = 60, crop = None, gauge = [40,40]) :
    # Find height ratio
    height_ratio = gauge[1] / float(gauge[0])

    # Open image, resize and posterize
    with open(path) as fp :
        # Open image
        image = Image(file=fp)
        # Crop
        if crop != None :
            image.crop(crop['x'], crop['y'], crop['w'] + crop['x'], crop['h'] + crop['y'])
            # Resize to width and height ratio
            resize(image, width, height_ratio)
            # Get data
            data = get_data(PImage.open(StringIO.StringIO(image.make_blob('ppm'))))
            # Posterize image to fewer colors
    return posterize(data, colors)
开发者ID:arnfred,项目名称:Knitwit,代码行数:19,代码来源:pattern.py

示例8: renderAnimation

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
def renderAnimation(animationName):
    print("Rendering animation: " + animationName)
    dirToFramesMapping = dict()

    animationDirectory = workingDirectory + animationName + "/"

    for key, value in directions.items():

        frameBuffer = Image(filename=(animationDirectory + animationName + "_" + value + ".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

        dirToFramesMapping[key] = frameBuffer

    directionAnimations = dict()

    for key, value in dirToFramesMapping.items():
        directionAnimationBuffer = Image(width=frameWidth, height=frameHeight)
        directionAnimationBuffer.composite(value, 0, 0)

        directionAnimations[key] = directionAnimationBuffer

    animation = Image(width=frameWidth, 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")
开发者ID:JeremyWildsmith,项目名称:JevaEngine_old,代码行数:47,代码来源:createparpgspritesheet.py

示例9: pathwalk

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
    color1 = color[0:3]
    color2 = color[3:6]
    color3 = color[6:9]
    # --------------------------------------------------------------

    # ----------get the base layer texture--------------------------
    Scenes = pathwalk('.\\SceneData\\')
    randomScene = random.choice(Scenes)
    randomScene = randomScene[0] + randomScene[1]
    # print(randomScene)
    randomSceneImage = Image(filename=randomScene)

    widthRange = randomSceneImage.size[0] - 100
    heightRange = randomSceneImage.size[1] - 32

    randomSceneImage.crop(left=random.randint(0, widthRange), top=random.randint(0, heightRange), width=100, height=32)
    # randomSceneImage.save(filename='.\\photoWand\\'+str(j+1) + '_texture.jpg')
    # --------------------------------------------------------------

    # ----------create the base layer, base texture +base color-----
    baseImage = Image(width=100, height=32, background=Color('rgb('+str(color1[0])+','+str(color1[1])+','+str(color1[2])+')'))

    # print('base_color = ' + 'rgb('+str(color1[0])+','+str(color1[1])+','+str(color1[2])+')')
    baseImage.composite_channel(channel='undefined', image=randomSceneImage, operator='blend', left=0, top=0)
    baseImage.gaussian_blur(4, 10)
    baseImage.resolution = (96, 96)
    # --------------------------------------------------------------

    # -----generate font--------------------------------------------
    word = python2access.randomWords()
    fonts = pathwalk('.\\googleFonts\\')
开发者ID:dailuo,项目名称:ImageMagick,代码行数:33,代码来源:GeneratePhotoWand.py

示例10: benchmark

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
def benchmark(source):
    """
    run through all tests, timing along the way

    timeit gets mentioned many times:
    http://docs.python.org/3.4/library/timeit.html
    """

    print("Testing moments: ") 
    start_time = time.time()

    print("making path:")
    step_time = time.time()    
    pic = Path(source)
    print(time.time() - step_time, "seconds")
    print("")

    
    print("loading path:")
    step_time = time.time()    
    img = pic.load()
    print(time.time() - step_time, "seconds")
    print("")

    #13.3232491016 seconds:
    ## print "make thumbs: (all)"
    ## step_time = time.time()    
    ## img.make_thumbs()
    ## print time.time() - step_time, "seconds"
    ## print ""

    ## print "removing thumbs: (all)"
    ## step_time = time.time()    
    ## shutil.rmtree("sized")
    ## print time.time() - step_time, "seconds"
    ## print ""

    #3.2377550602 seconds:
    ## print "make thumbs: (tiny)"
    ## step_time = time.time()    
    ## img.make_thumbs(["tiny"])
    ## print time.time() - step_time, "seconds"
    ## print ""

    ## print "removing thumbs: (tiny)"
    ## step_time = time.time()    
    ## shutil.rmtree("sized")
    ## print time.time() - step_time, "seconds"
    ## print ""

    #now break it down to steps:

    #0.000612020492554 seconds
    ## print "make thumbs dirs()"
    ## step_time = time.time()    
    ## img.make_thumb_dirs()
    ## print time.time() - step_time, "seconds"
    ## print ""

    ## print "removing thumbs dirs"
    ## step_time = time.time()    
    ## shutil.rmtree("sized")
    ## print time.time() - step_time, "seconds"
    ## print ""

    #0.00586199760437 seconds
    print("Open image with PIL: ") 
    step_time = time.time()
    image = PILImage.open(source)
    print(time.time() - step_time, "seconds")
    print("")

    print("show sizes: ") 
    step_time = time.time()
    print(image.size)
    print(time.time() - step_time, "seconds")
    print("")

    #0.56491112709 seconds
    print("Copy image buffer in PIL: ") 
    step_time = time.time()
    square = image.copy()
    print(time.time() - step_time, "seconds")
    print("")

    print("resize max: ") 
    step_time = time.time()
    pre_crop = resize_max(400, image.size[0], image.size[1])
    print(pre_crop)
    print(time.time() - step_time, "seconds")
    print("")
    
    #0.108213186264 seconds
    print("Square image (includes copy)") 
    step_time = time.time()
    square = img._square_image(square)    
    print(time.time() - step_time, "seconds")
    print("")

    #xl = 2880
#.........这里部分代码省略.........
开发者ID:charlesbrandt,项目名称:templates,代码行数:103,代码来源:resize-benchmarks.py

示例11: min

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
    lines[2] = min(difference_to_middle_bottom)

    return lines


#For all the png in the folder
for filename in glob.glob("*-t.png"):
    im = Image(filename=filename)
    #Save the widht and height of the thumbnail
    th = im.height
    tw = im.width
    #Crop the image
    l = crop_image(im)
    top = l[1]
    bottom = l[2]
    im.crop(0,l[1],im.width,l[2])
    #We rotate so we can use the same code!
    im.rotate(90)
    print im.height, im.width
    l = crop_image(im)
    im.crop(0,l[1],im.width,l[2])
    left = l[1]
    right = l[2]
    im.rotate(-90)
    #We open the original image so we can crop it too
    original = filename.replace('-t','')
    oim = Image(filename=original)
    ow = oim.width
    oh = oim.height
    oim.crop((left * ow) /tw,(top * oh) / th,(right * ow) / tw,(bottom * oh) / th)
    im.save(filename=filename+'crop.png')
开发者ID:digglam,项目名称:assistant,代码行数:33,代码来源:cropping.py

示例12: download_image

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
def download_image(request, datafile_id, region, size, rotation,
                   quality, format=None): #@ReservedAssignment
    # Get datafile (and return 404 if absent)
    try:
        datafile = DataFile.objects.get(pk=datafile_id)
    except DataFile.DoesNotExist:
        return HttpResponseNotFound()

    is_public = datafile.is_public()
    if not is_public:
        # Check users has access to datafile
        if not has_datafile_download_access(request=request,
                                            datafile_id=datafile.id):
            return HttpResponseNotFound()

    buf = StringIO()
    try:
        file_obj = datafile.get_image_data()
        if file_obj is None:
            return HttpResponseNotFound()
        from contextlib import closing
        with closing(file_obj) as f:
            with Image(file=f) as img:
                if len(img.sequence) > 1:
                    img = Image(img.sequence[0])
                # Handle region
                if region != 'full':
                    x, y, w, h = map(int, region.split(','))
                    img.crop(x, y, width=w, height=h)
                # Handle size
                if size != 'full':
                    # Check the image isn't empty
                    if 0 in (img.height, img.width):
                        return _bad_request('size', 'Cannot resize empty image')
                    # Attempt resize
                    if not _do_resize(img, size):
                        return _bad_request('size',
                                            'Invalid size argument: %s' % size)
                # Handle rotation
                if rotation:
                    img.rotate(float(rotation))
                # Handle quality (mostly by rejecting it)
                if quality not in ['native', 'color']:
                    return _get_iiif_error('quality',
                    'This server does not support greyscale or bitonal quality.')
                # Handle format
                if format:
                    mimetype = mimetypes.types_map['.%s' % format.lower()]
                    img.format = format
                    if mimetype not in ALLOWED_MIMETYPES:
                        return _invalid_media_response()
                else:
                    mimetype = datafile.get_mimetype()
                    # If the native format is not allowed, pretend it doesn't exist.
                    if mimetype not in ALLOWED_MIMETYPES:
                        return HttpResponseNotFound()
                img.save(file=buf)
                response = HttpResponse(buf.getvalue(), content_type=mimetype)
                response['Content-Disposition'] = \
                    'inline; filename="%s.%s"' % (datafile.filename, format)
                # Set Cache
                if is_public:
                    patch_cache_control(response, public=True, max_age=MAX_AGE)
                else:
                    patch_cache_control(response, private=True, max_age=MAX_AGE)
                return response
    except WandException:
        return HttpResponseNotFound()
    except ValueError:
        return HttpResponseNotFound()
    except IOError:
        return HttpResponseNotFound()
开发者ID:keithschulze,项目名称:mytardis,代码行数:74,代码来源:iiif.py

示例13: crop

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
def crop(jpeg, width=128, height=171):
    """Returns a cropped version of an image"""
    img = Image(blob=jpeg)
    img.crop(left=3, top=3, width=width, height=height)
    return img.make_blob()
开发者ID:wtsi-hgi,项目名称:hgi-reports,代码行数:7,代码来源:humgen_farmers_standup.py

示例14: __init__

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
class Panel:
    def __init__(self, background=None, chars=None, scene=None, doublewide=False):
        if background is None:
            background = randomize_background()
        self.background = Image(filename=background)

        self.doublewide = doublewide
        if self.doublewide is True:
            self.background.crop(0, 0, self.background.height, self.background.height)
            self.background.transform(resize='1000x500^')
            self.background.transform('1000x500')
        else:
            self.background.crop(0, 0, self.background.height, self.background.height)
            self.background.transform(resize='500')
            self.background.transform(resize='500x500')

        self.chars = chars
        self.scene = scene
        draw.font = 'plugins/py_toon/fonts/DejaVuSansMono.ttf'
        draw.font_size = 15
        draw.text_kerning = 1
        draw.text_alignment = 'left'

    def setup(self):
        self.add_characters()
        self.speech_bubbles()
        self.background = self.render()
        return self.background
        
    def speech_bubbles(self):
        curx = 15
        cury = 15

        for action in self.scene[1]:

            actor = action[0]
            line = action[1]
            if not line:
                continue
            line = textwrap.fill(line, 20)

            metrics = draw.get_font_metrics(self.background, line, True)

            ctext = int(metrics.text_width / 2.0)
            draw.fill_color = Color('white')
            draw.stroke_color = Color('black')
            draw.stroke_width = 1.0

            char_center = actor.img.x + int(actor.img.width / 2.0)
            text_center = int(metrics.text_width / 2.0)

            if len(self.scene[1]) == 1:
                cury = randrange(50, 125 + 20)
            else:
                max_y = cury + 20
                if max_y < 1: max_y = 245
                cury = randrange(cury, max_y)
            curx = char_center - text_center
            if curx < 25: curx = 25
            if curx > self.background.width - int(metrics.text_width):
                curx = self.background.width - int(metrics.text_width) - 15

            curx = int(curx)
            cury = int(cury)

            if line.strip() != '':
                draw.round_rectangle(curx - 10, cury, curx + metrics.text_width + 10, cury + metrics.text_height + 5, 5, 5)

                draw.fill_color = Color('black')

                draw.text(curx, cury + 15, line)
                curx += metrics.text_width + 10
                cury += int(metrics.text_height + 10)

    def add_characters(self):
        parts = self.background.width / len(self.chars.keys())

        curx = 0
        cury = 0

        char_count = 0
        for i in self.chars.items():
            char = i[1]

            if self.doublewide is True:
                #char.img.resize(175, 175)
                char.img.transform(resize='x150')
            else:
                char.img.resize(125, 125)

            ### contain the character in this "box"
            char_pos = curx + parts - char.img.width
            print 'char_pos:', char_pos
            if char_pos < 1:
                return 'Not enough space to fit everybody.'
            curx = randrange(curx, char_pos)

            cury = self.background.height - char.img.height

            char.img.x = curx
#.........这里部分代码省略.........
开发者ID:Senso,项目名称:Donginger,代码行数:103,代码来源:pytoon.py

示例15: Card

# 需要导入模块: from wand.image import Image [as 别名]
# 或者: from wand.image.Image import crop [as 别名]
class Card(object):
	"""Individual object containing an image and actions to manipulate it.
	Posible kwargs to __init__ are filename, file, image, blob. it will load the image from there"""
	def __init__(self, *args, **kwargs):
		"""Init a new cards with *img* being a wand.image.Image object"""
		self.img = Image(*args, **kwargs)
		self.border = None
		self.changed = True
		self.pixmap()

	def __del__(self):
		self.img.destroy()

	def format(self, fmt=None):
		if fmt is None:
			return self.img.format.lower()
		else:
			self.img.format = fmt

	@set_changed
	def resize(self, width, height, newres=300):
		"""Resize this card to (*width*, *height*) inches, with a resolution of *newres*"""
		self.img.transform(resize=str(int(width*newres)) + "x" + str(int(height*newres)) + "!")
		self.img.reset_coords()
		self.img.resolution = (newres, newres)
		return newres

	def width(self):
		return self.img.size[0]

	def height(self):
		return self.img.size[1]

	def reset_coords(self):
		self.img.reset_coords()

	@set_changed
	def set_border(self, border):
		"""Set a new *border* for this card"""
		if self.border is not None:
			self.del_border()
		self.border = border
		with Color(self.border.colour) as colour:
			self.img.border(colour, self.border.wide, self.border.wide)

	@set_changed
	def crop(self, *args, **kwargs):
		"""Crop this card *top*, *bottom*, *left* and *right* pixels"""
		w, h = self.img.size
		if "right" in kwargs:
			kwargs["right"] = w - kwargs["right"]
		if "bottom" in kwargs:
			kwargs["bottom"] = h - kwargs["bottom"]
		self.img.crop(*args, **kwargs)
		self.reset_coords()

	def del_border(self):
		"""Remove the border of this card"""
		if self.border is not None:
			w = self.border.wide
			self.crop(top=w, bottom=w, right=w, left=w)
			self.border = None
			self.changed = True

	@set_changed
	def trim(self, fuzz=13):
		self.img.trim(fuzz=fuzz)
		self.reset_coords()

	def save_as(self, filename):
		"""Save this card in a file named *filename*"""
		self.img.save(filename = filename)

	def split(self, rows, cols, separation=0):
		"""Divide this cards in *rows* by *cols* cards, and returns a list"""
		width, hight = self.img.size
		width, hight = (int(width), int(hight))
		cardWidth = (width - separation * (cols-1)) / cols
		cardHight = (hight - separation * (rows-1)) / rows
		res = []
		for i in range(rows):
			for j in range(cols):
				with self.img.clone() as clon:
					clon.crop(top=i*cardHight+i*separation, width=cardWidth, left=j*cardWidth+j*separation, height=cardHight)
					clon.reset_coords()
					res.append(Card(image=clon))
		return res

	@set_changed
	def round_corners(self):
		"""Round the corners of the card (setting them to alpha)"""
		pass

	def clone(self):
		c = Card(image=self.img.clone())
		c.border = self.border
		return c

	def pixmap(self):
		"""Update and returns the pixmap (QPixmap) of the contained image"""
#.........这里部分代码省略.........
开发者ID:Ja-vi,项目名称:pnp,代码行数:103,代码来源:card.py


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