All pastes #1896450 Raw Edit

Mine

public text v1 · immutable
#1896450 ·published 2010-07-08 03:08 UTC
rendered paste body
#!/usr/bin/env python
#
# HvZCardCreator: backend to create id cards for pyHvZPlayer


import Image, ImageDraw, ImageFont
import qrcode, sys, tempfile, os




def createCard(player_name, player_id, avatar_loc, card_width, save_loc):
    """Creates a card containing an avatar, the players name, the players id, and a QR Code."""
    

    # Create the card image and draw surface
    card_height = .6 * card_width
    card = Image.new("RGB", (int(card_width), int(card_height)), "#FFFFFF")
    card_draw = ImageDraw.Draw(card)

    # Load and scale the avatar
    try:
        avatar = Image.open(avatar_loc)
    except IOError:
        raise Exception, "Could not open avatar file."

    avatar.thumbnail((int(card_width * .25), int(card_width * .25)))

    # Create a QR Code containing the player name and ID
    qr_encoder = qrcode.Encoder()
    qr_image = qr_encoder.encode(player_name + '|' + player_id, version=2, mode=qr_encoder.mode.BINARY, eclevel=qr_encoder.eclevel.L, width=int(card_width * .4))

    # Create a temporary file and save the QR Code to it
    (fd, fname) = tempfile.mkstemp()
    qr_f = os.fdopen(fd, "w+b")
    qr_image.save(qr_f, "png")

    # Load a font to write the name and id
    font = ImageFont.truetype("standard_font.ttf", 16)


    #####
    # Build the card image
    #####

    # place avatar
    card.paste(avatar, (int(card_width * .1), int(card_width * .1)))
    
    # build a box around the avatar
    card_draw.rectangle(((card_width * .1, card_width * .1), (avatar.size[0] + card_width * .1, avatar.size[1] + card_width * .1)), outline=0)
   
    # place text
    card_draw.text((card_width * .1, avatar.size[1] + card_width * .1 + 10), player_name, font=font, fill=0)
    card_draw.text((card_width * .1, avatar.size[1] + card_width * .1 + 26), player_id, font=font, fill=0)

    # place QR Code
    image = Image.open(fname)
    card.paste(image, (int(card_width * .5), int(card_width * .1)))



    # Save the card
    try:
        card.save(save_loc)
    except IOError:
        raise Exception, "Could not save to card location."