本文整理汇总了Python中PIL.ImageDraw.Draw类的典型用法代码示例。如果您正苦于以下问题:Python Draw类的具体用法?Python Draw怎么用?Python Draw使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Draw类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: drawer
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
示例2: draw_text
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: text
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
示例4: mapdraw
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)
示例5: create_noise_dots
def create_noise_dots(image, color, width=3, number=30):
draw = Draw(image)
w, h = image.size
while number:
x1 = random.randint(0, w)
y1 = random.randint(0, h)
draw.line(((x1, y1), (x1 - 1, y1 - 1)), fill=color, width=width)
number -= 1
return image
示例6: inimagehandler
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())
示例7: inimagehandler
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())
示例8: noise
def noise(self, image, number=50, level=2, color=None):
width, height = image.size
dx = width / 10
width -= dx
dy = height / 10
height -= dy
draw = Draw(image)
for i in xrange(number):
x = int(random.uniform(dx, width))
y = int(random.uniform(dy, height))
draw.line(((x, y), (x + level, y)), fill=color if color else self._color, width=level)
return image
示例9: drawer
def drawer(image, text):
width, height = image.size
dx = width / 10
width = width - dx
dy = height / 10
height = height - dy
draw = Draw(image)
for i in xrange(number):
x = int(random.uniform(dx, width))
y = int(random.uniform(dy, height))
draw.line(((x, y), (x + level, y)), fill=color(), width=level)
return image
示例10: point
def point(self, patterns, color='black'):
hasher = md5()
draw = Draw(self.image)
for y, pattern in enumerate(patterns):
pattern_data = pattern.pattern_data
hasher.update(pattern_data)
points = [
(x, y)
for x, dot in enumerate(_to_bit(pattern_data)) if dot == '1'
]
draw.point(points, color)
self.hash = hasher.hexdigest()
示例11: colormap
def colormap(args):
rangelen = args['max'] - args['min']
rangemid = args['min'] + (rangelen / 2)
rangemax = args['max']
rangemin = args['min']
cr2 = rgb2hex.linear_gradient(args['colors'][1],args['colors'][2],(int(rangelen/2*1000))+1)['hex']
cr1 = rgb2hex.linear_gradient(args['colors'][0],args['colors'][1],(int(rangelen/2*1000))+1)['hex']
dictlist = {}
# === PAIR DATA WITH COLOR MAP ===
for y,sl in enumerate(args['data']): # for each sublist within dataset (row)
for x,i in enumerate(sl): # for each point in sublist (column)
val = args['colors'][1]
#top half of data range
if i > rangemid:
if i <= rangemax:
val = cr2[int((i - (rangemin + rangelen/2)) * 1000)]
else:
val = args['colors'][2]
#bottom half of data range
elif i < rangemid:
if i >= rangemin:
val = cr1[int((i - rangemin) * 1000)]
else:
val = args['colors'][0]
# mask
if 'mask' in args:
if i <= args['mask'][0]:
val = args['mask'][1]
# add to dict
if val in dictlist:
dictlist[val].append((x,y))
else:
dictlist[val] = [(x,y)]
args['datamap'] = dictlist
# ===== COLORBAR CREATION =====
clr = (cr1 + cr2)
clr = clr[::-1000]
widthclr = args['colorbar']
heightclr = len(clr)
imgclr = Image.new("RGB",(widthclr,heightclr),"white")
drawclr = Draw(imgclr)
for y,val in enumerate(clr):
for x in range(widthclr):
drawclr.point((x,y),getrgb(str(val)))
return args, imgclr
示例12: draw_compiled
def draw_compiled(img, xyc_it, thickness=1):
"""Draws a sequence of x,y,color tuples onto an image.
xyc_it: iterator of x,y,color tuples. The color of the first entry is
discarded, all other colors are used as the respective line's color"""
center_x, center_y = map(lambda n: n / 2, img.size)
d = Draw(img, "RGBA")
(x, y), _ = next(xyc_it)
x, y = x * img.scale + center_x, y * img.scale + center_y
for ((x2, y2), c) in xyc_it:
x2, y2 = x2 * img.scale + center_x, y2 * img.scale + center_y
d.line((x, y, x2, y2), c, width=thickness)
x, y = x2, y2
示例13: generate_letter
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
示例14: generate_capture
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
示例15: drawclock
def drawclock(fontpath,fontsize,fgcolor,bgcolor,style,case,drawLEDs=False):
# init font
scaledfontsize = pt2pxy(fontsize)
font = ImageFont.truetype(size=scaledfontsize,filename=fontpath)
lines = decodeLetters(style,case)
img = Image.new("RGBA", (pt2pxx(WIDTH), pt2pxy(HEIGHT)))
draw = Draw(img)
draw.rectangle(((0,0), (pt2pxx(WIDTH),pt2pxy(HEIGHT))), fill=bgcolor)
for h in corner_holes:
drawhole(draw,h,fgcolor)
if drawLEDs:
drawleds(draw,led_xs,led_ys,fgcolor)
drawletters(draw,lines,font,case,led_xs,led_ys,fgcolor)
del draw
return img