本文整理汇总了Python中PIL.ImageDraw.Draw.text方法的典型用法代码示例。如果您正苦于以下问题:Python Draw.text方法的具体用法?Python Draw.text怎么用?Python Draw.text使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PIL.ImageDraw.Draw
的用法示例。
在下文中一共展示了Draw.text方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: text
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def text(self, image, fonts, font_sizes=None, drawings=None, squeeze_factor=0.75, color=None):
color = color if color else self._color
fonts = tuple([truetype(name, size)
for name in fonts
for size in font_sizes or (65, 70, 75)])
draw = Draw(image)
char_images = []
for c in self._text:
font = random.choice(fonts)
c_width, c_height = draw.textsize(c, font=font)
char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0))
char_draw = Draw(char_image)
char_draw.text((0, 0), c, font=font, fill=color)
char_image = char_image.crop(char_image.getbbox())
for drawing in drawings:
d = getattr(self, drawing)
char_image = d(char_image)
char_images.append(char_image)
width, height = image.size
offset = int((width - sum(int(i.size[0] * squeeze_factor)
for i in char_images[:-1]) -
char_images[-1].size[0]) / 2)
for char_image in char_images:
c_width, c_height = char_image.size
mask = char_image.convert('L').point(lambda i: i * 1.97)
image.paste(char_image,
(offset, int((height - c_height) / 2)),
mask)
offset += int(c_width * squeeze_factor)
return image
示例2: draw_text
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def draw_text( data, text, color = 255, pos = 'lr' ):
from PIL.Image import fromarray
from PIL.ImageDraw import Draw
from PIL import ImageFont
from numpy import asarray
font = ImageFont.load_default()
image = fromarray( data )
draw = Draw( image )
w, h = draw.textsize( text, font = font )
position = {
'ul': lambda iw, ih, tw, th: ( 2, 0 ),
'ur': lambda iw, ih, tw, th: ( iw - tw - 2, 0 ),
'll': lambda iw, ih, tw, th: ( 2, ih - th ),
'lr': lambda iw, ih, tw, th: ( iw - tw - 2, ih - th ),
}
pos = position[ pos ]( data.shape[ 1 ], data.shape[ 0 ], w, h )
draw.text( pos, text, fill = color, font = font )
del draw
return asarray( image )
示例3: drawer
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def drawer(image, text):
draw = Draw(image)
char_images = []
for c in text:
font = random.choice(fonts)
c_width, c_height = draw.textsize(c, font=font)
c_height *= 2
char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0))
char_draw = Draw(char_image)
char_draw.text((0, 0), c, font=font, fill=color())
char_image = char_image.crop(char_image.getbbox())
for drawing in drawings:
char_image = drawing(char_image)
char_images.append(char_image)
width, height = image.size
offset = int((width - sum(int(i.size[0] * squeeze_factor)
for i in char_images[:-1])
- char_images[-1].size[0]) / 2)
for char_image in char_images:
c_width, c_height = char_image.size
mask = char_image.convert('L').point(lambda i: i * 1.97)
image.paste(char_image,
(offset, int((height - c_height) / 2)),
mask)
offset += int(c_width * squeeze_factor)
return image
示例4: inimagehandler
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def inimagehandler(self, code, message, params):
im = new('RGBA', (int(params['width']), int(params['height'])))
im.putalpha(new('1', (int(params['width']), int(params['height']))))
draw = Draw(im)
for count, line in enumerate(message.strip().split('\n')):
draw.text((12,15*(count+1)), line, fill='#000000')
fh = StringIO()
im.save(fh, PIL_TYPE_MAPPING[params['format']])
fh.seek(0)
return Response(params['format'], fh.read())
示例5: inimagehandler
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def inimagehandler(self, code, message, params):
im = new("RGBA", (int(params["width"]), int(params["height"])))
im.putalpha(new("1", (int(params["width"]), int(params["height"]))))
draw = Draw(im)
for count, line in enumerate(message.strip().split("\n")):
draw.text((12, 15 * (count + 1)), line, fill="#000000")
fh = StringIO()
im.save(fh, PIL_TYPE_MAPPING[params["format"]])
fh.seek(0)
return Response(params["format"], fh.read())
示例6: generate_letter
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def generate_letter(char, font_size, font_name):
img_dim = (font_size + font_size / 2,) * 2
img = new_image("RGB", img_dim, (0, 0, 0))
img_draw = Draw(img)
#font = PIL.ImageFont.ImageFont()
#font.font = PIL.ImageFont.truetype(font_name, font_size)
#font.color = tuple( [randrange(126, 256) for i in range(3)] )
font = PIL.ImageFont.truetype(font_name, font_size)
color = tuple( [randrange(126, 256) for i in range(3)] )
img_draw.text((0, 0), char, color, font)
#img = img_draw.flush()
img = img.rotate(randrange(-30, 30), BICUBIC)
mask = new_image("L", img.size, 0)
mask.paste(img, (0, 0))
return img, mask
示例7: generate_capture
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def generate_capture(request):
"""
You can visit the view with GET params like k, b, f to custom the capture.
b indicates background color, and f foreground color.
The value of color should be an integer, which will be convert to a hex color value. That is to say the value
of a color should not be less than 0 or larger than 16777215.
k indicates the key of the capture. It should exist in session before this view is visited, otherwise A 404 error
will be throw out.
And once the view is visited, the answer of the capture will be set a key in session which k indicates.
"""
keyName, bcolor, fcolor = DEFAULT_CAPTURE_ID, DEFAULT_BACKGROUND, DEFAULT_FOREGROUND
if 'k' in request.GET:
if request.GET['k'] in request.session:
keyName = request.GET['k']
else:
raise Http404()
try:
if 'b' in request.GET:
bcolor = '#{:0>6.6s}'.format('%x' % max(min(int(request.GET['b']), 16777215), 0))
if 'f' in request.GET:
fcolor = '#{:0>6.6s}'.format('%x' % max(min(int(request.GET['f']), 16777215), 0))
except:
raise Http404()
ver_fun = snippets[randint(0, len(snippets) - 1)]
x, y = ver_fun[2](), ver_fun[3]()
request.session[keyName] = '%r' % ver_fun[1](x, y)
img = Image.new("RGB", (DEFAULT_WIDTH, DEFAULT_HEIGHT), bcolor)
draw = Draw(img)
font = ImageFont.truetype('font/SourceCodePro-Regular.ttf', DEFAULT_FONT_SIZE)
for i in xrange(0, 3):
draw.line([(0, randint(0, DEFAULT_HEIGHT)), (DEFAULT_WIDTH, randint(1, DEFAULT_HEIGHT))],
fill='#{:0>6.6s}'.format('%x' % randint(0, 16777215)))
if x < 0:
x = '(%s)' % x
if y < 0:
y = '(%s)' % y
text = ver_fun[0] % (x, y)
x, y = font.getsize(text)
draw.text((DEFAULT_WIDTH / 2 - x / 2, DEFAULT_HEIGHT / 2 - y / 2), text, font=font, fill=fcolor)
response = HttpResponse(mimetype='image/png')
img.save(response, 'PNG')
return response
示例8: mapdraw
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def mapdraw(args,colorbar):
img = Image.new('RGB',(args['xlen'],args['ylen']),'white')
draw = Draw(img)
for key,value in args['datamap'].iteritems():
draw.point(value,getrgb(str(key)))
img2 = img.resize((args['y'],args['y']), Image.BILINEAR)
imgclr = colorbar.resize((args['colorbar'],img2.size[1]), Image.BILINEAR)
# ===== ENTIRE IMAGE CREATION W/ TEXT=====
imgbox = Image.new('RGB',((300+args['y']+args['colorbar']),(img2.size[1]+200)),args['background'])
imgbox.paste(img2,(100,100))
imgbox.paste(imgclr,((200+img2.size[0]),100))
drawbox = Draw(imgbox)
title = args['title']
titlesize = 50 # future user input
font = truetype("/library/fonts/Arial.ttf",titlesize)
smfontsize = 30 # future user input
smfont = truetype("/library/fonts/Arial.ttf",smfontsize)
titlewidth = font.getsize(title)[0]
drawbox.text(((imgbox.size[0]/2 - titlewidth/2), titlesize/2),title,(0,0,0),font=font)
drawbox.text(((imgbox.size[0] - 95),100),str(args['max']),(0,0,0),font=smfont)
drawbox.text(((imgbox.size[0] - 95),(100 + img2.size[1] - smfontsize)),str(args['min']),(0,0,0),font=smfont)
imgbox.show()
if 'title' in args:
title = args['title']+'_'+str(args['min'])+'_'+str(args['max'])+'.png'
else:
title = 'output_'+str(args['min'])+'_'+str(args['max'])+'.png'
imgbox.save(args['save']+'/'+title)
示例9: draw_text
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
def draw_text(image, text, font_size):
font = truetype(join(current_dir, 'static/font.ttf'), font_size)
color = '#5C87B2'
draw = Draw(image)
char_images = []
for ch in text:
c_width, c_height = draw.textsize(ch, font=font)
char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0))
char_draw = Draw(char_image)
char_draw.text((0, 0), ch, font=font, fill=color)
char_image = char_image.crop(char_image.getbbox())
char_images.append(char_image)
width, height = image.size
total = len(char_images)
for i, char_image in enumerate(char_images):
c_width, c_height = char_image.size
mask = char_image.convert('L').point(lambda i: i * 1.97)
upper = int((height - c_height) / 2)
left = int((width * (i + 1) / (total + 1)) - c_width / 2)
image.paste(char_image, (left, upper), mask)
return image
示例10: truetype
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
filename = 'button-small-%s.png' % label.lower().replace(' ', '-')
# Hintergrund zusammenbauen
gradients = Image.open('generate-button-small.png')
y = 0
height = 23
background = gradients.crop((0, y, 200, height))
right = gradients.crop((203, 0, 208, height))
# Font laden und rausbekommen, wie gross der Button werden muss
ttf = '/Library/Fonts/Arial Narrow Bold.ttf'
font = truetype(ttf, 12, encoding='unic')
text_width, _ = font.getsize(label)
width = text_width + 2 * args.padding
# jetzt den Hintergrund in den Button reinkopieren
button = Image.new('RGBA', (width, height * 2))
button.paste(background, (0, 0))
button.paste(flip(background), (0, height))
button.paste(right, (width-5, 0))
button.paste(flip(right), (width-5, height))
# dann die Beschriftung reinmalen
draw = Draw(button)
draw.text((args.padding, 0+3), label, font=font, fill=args.text_color)
draw.text((args.padding, 23+4), label, font=font, fill=args.text_color)
# und schliesslich nur noch den Button speichern
#button.show()
button.save(filename, 'PNG')
示例11: truetype
# 需要导入模块: from PIL.ImageDraw import Draw [as 别名]
# 或者: from PIL.ImageDraw.Draw import text [as 别名]
icon_height = 0
# Font laden und rausbekommen, wie gross der Button werden muss
ttf = '/Library/Fonts/Arial Narrow Bold.ttf'
font = truetype(ttf, 12, encoding='unic')
text_width, _ = font.getsize(label)
width = text_width + 2 * args.padding + icon_width
# jetzt den Hintergrund in den Button reinkopieren
button = Image.new('RGBA', (width, height * 2))
button.paste(background, (0, 0))
button.paste(flip(background), (0, height))
button.paste(right, (width-5, 0))
button.paste(flip(right), (width-5, height))
# das Icon muss auch rein, wenn wir eines haben
if icon:
alpha_channel = icon.split()[3]
mask = Image.eval(alpha_channel, lambda a: 255 if a >=128 else 0)
for offs in [0, height]:
button.paste(icon, (7, offs + int(height/2.0-icon_height/2.0)), mask)
# dann die Beschriftung reinmalen
draw = Draw(button)
draw.text((icon_width + args.padding, upper_text), label, font=font, fill=args.text_color)
draw.text((icon_width + args.padding, lower_text), label, font=font, fill=args.text_color)
# und schliesslich nur noch den Button speichern
#button.show()
button.save(filename, 'PNG')