All pastes #2057554 Raw Edit

Someone

public python v1 · immutable
#2057554 ·published 2011-05-12 18:58 UTC
rendered paste body
#/usr/bin/env python# -*- coding: utf-8 -*- ##Copyright (C) 2011 Carlos Pais#Licença: WTFPL <http://sam.zoy.org/wtfpl/COPYING>"""Cria um conjunto de imagens de A a Z de acordo com o fundo pretendido.Dependências:-Python 2.7.1 <http://python.org/download/releases/2.7.1/>-Python Imaging Library (PIL) 2.7 <http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil>Como usar?-Guardar este código num ficheiro com extensão 'py'.-Dar duplo-clique no script ou chamá-lo através de uma consola.Nota: É possível especificar por argumento um fundo e uma fonte. Caso o fundo não sejaespecificado, o programa irá procurar por uma imgem bitmap na directoria em que estáe assumir que esse é o fundo desejado.Caso a fonte não seja especificada, o programa tenta primeiro procurar umafonte localmente, e caso não encontre, procura pela fonte 'DejaVuSans.ttf' nasfontes do sistema."""from PIL import Image, ImageFont, ImageDrawimport stringimport os, sysfrom os.path import join, existsdef pesquisa_local(ext):    for file in os.listdir("."):        if file[-len(ext):] == ext:            return file                return ""    args = sys.argvif len(args) > 3:    print "*ERROR* Sintaxe: " + args[0] + " [FUNDO] [FONTE]"    sys.exit()args.append("")args.append("")bg_name = args[1]fontpath = args[2]if not fontpath:     #Procura por fontes na pasta local    fontpath = pesquisa_local("ttf")        #Caso não encontre, tenta buscar uma fonte às fontes do sistema    if not fontpath:        if os.name == "nt":            fontpath = "C:\Windows\Fonts\DejaVuSans.ttf"        elif os.name == "posix":            fontpath = "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf"                if not exists(fontpath):        print "Não foi encontrada uma fonte válida. A sair..."        sys.exit()#Procura imagem de fundo na pasta localif not bg_name:    bg_name = pesquisa_local("bmp")        if not bg_name:        print "Não foi encontrada uma imagem de fundo válida. A sair..."        sys.exit()print "A usar a fonte: " + fontpathprint "A usar como fundo: " + bg_name#cria fonteimg = Image.open(bg_name)img_width, img_height = img.sizetry:    ext = "." + img.format.lower()except AttributeError:    print "Formato de imagem desconhecido. A sair..."    sys.exit()    del imgfont_size =  int(img_width - img_width * 0.1)font = ImageFont.truetype(fontpath, font_size) # use a truetype fontdirname = "imagens-SO2"color = "black"x = img_width * 0.1y = -img_height * 0.1if not exists(dirname): os.mkdir(dirname)for letter in string.uppercase:    print "A processar imagem: " + letter    img_letter = Image.new('RGBA', (img_width, img_height), (0, 0, 0, 0)) # Create a blank image    draw = ImageDraw.Draw(img_letter)    draw.text((x, y), letter, font=font, fill=color)        img_bg = Image.open(bg_name)        img_bg.paste(img_letter, None, img_letter)    img_bg.save(join(dirname, letter + ext))    if ext != ".bmp":    try:        for letter in string.uppercase:            filepath = join(dirname, letter + ext)            img = Image.open(filepath)            try:                r, g, b, a = img.split()            except ValueError:                r, g, b = img.split()                            img = Image.merge("RGB", (r, g, b))            img.save(join(dirname, letter + ".bmp"))            os.remove(join(dirname, letter + ext))            print letter + ".png" + " convertida para " +  letter + ".bmp"    except e:        print e        print "Não foi possível converter as imagens para Bitmap."