def captcha_image(self, font_file, band_name): # determine the starting font size font_size = 1 font = ImageFont.truetype(font_file, font_size) width, height = font.getsize(band_name) while width < image_width and height < image_height: font_size += 1 font = ImageFont.truetype(font_file, font_size) width, height = font.getsize(band_name) print width, height font_size -= 10 # attempts to account for increased kerning due to text warping and rotation image = captcha( drawings = [ background(color = background_color), text( fonts = [font_file], font_sizes = [font_size], drawings = [ warp(random.random(), random.random()), rotate(random.randint(5, 45)) ], color = text_color, squeeze_factor = random.randint(5, 7) / 10.0 ), noise( number = random.randint(50, 200), color = text_color ) ], width = image_width, height = image_height ) return image(band_name)
def __init__(self, chrt, size, opts, bw): self.chart = chrt self.options = opts self.w, self.h = size self.bw = bw self.buffer = wx.EmptyBitmap(self.w, self.h) self.bdc = wx.BufferedDC(None, self.buffer) self.chartsize = min(self.w, self.h) self.maxradius = self.chartsize/2 self.center = wx.Point(self.w/2, self.h/2) self.symbolSize = self.maxradius/16 self.smallSize = self.maxradius/18 self.fontSize = self.symbolSize self.fntMorinus = ImageFont.truetype(common.common.symbols, self.symbolSize) self.fntMorinusSmall = ImageFont.truetype(common.common.symbols, self.smallSize) self.fntText = ImageFont.truetype(common.common.abc, self.fontSize) self.fntTextSmall = ImageFont.truetype(common.common.abc, 3*self.fontSize/4) self.fntTextSmaller = ImageFont.truetype(common.common.abc, self.fontSize/2) self.signs = common.common.Signs1 if not self.options.signs: self.signs = common.common.Signs2 self.deg_symbol = u'\u00b0' self.SPACE = self.fontSize/5 self.LINE_HEIGHT = (self.SPACE+self.fontSize+self.SPACE) self.clrs = (self.options.clrdomicil, self.options.clrexal, self.options.clrperegrin, self.options.clrcasus, self.options.clrexil) self.hsystem = {'P':mtexts.txts['HSPlacidus'], 'K':mtexts.txts['HSKoch'], 'R':mtexts.txts['HSRegiomontanus'], 'C':mtexts.txts['HSCampanus'], 'E':mtexts.txts['HSEqual'], 'W':mtexts.txts['HSWholeSign'], 'X':mtexts.txts['HSAxial'], 'M':mtexts.txts['HSMorinus'], 'H':mtexts.txts['HSHorizontal'], 'T':mtexts.txts['HSPagePolich'], 'B':mtexts.txts['HSAlcabitus'], 'O':mtexts.txts['HSPorphyrius']}
def SetImgTitle(self, img, img_size, y): """Adds a title contered to the image's width. Args: img: a Python Image Libaray Image instance. img_size: a tuple of the width and height of the final image. y: the current height position in the image. """ draw = ImageDraw.Draw(img) # Print top title. top_font = ImageFont.truetype(self.IMG_TITLE_FONT, 18) top_title_size = top_font.getsize(self.IMG_TITLE) x = img_size[0]/2 - top_title_size[0]/2 draw.text((x, y), self.IMG_TITLE, font=top_font, fill=self.IMG_TITLE_COLOR) y += top_title_size[1] + 5 # Print sub title as a formatted date range. dates = [datetime.strptime(d, '%Y-%m-%d') for d in ( self.query_uri.query['start-date'], self.query_uri.query['end-date'] )] sub_title = ' - '.join([d.strftime('%b-%d-%Y') for d in dates]) sub_font = ImageFont.truetype(self.IMG_TITLE_FONT, 12) sub_title_size = sub_font.getsize(sub_title) x = img_size[0]/2 - sub_title_size[0]/2 draw.text((x, y), sub_title, font=sub_font, fill=self.IMG_TITLE_COLOR) self.SetImgCharts(img, y)
def get_font(fontpath): """Helper to find and return specified or default ImageFont.""" if (fontpath): print "Found Font!" return ImageFont.truetype(fontpath, 14) else: return ImageFont.load_default()
def resIdCode(request): token_id = request.GET.get('token_id') im = Image.open('/usr/workspace/news/static/test.png') draw = ImageDraw.Draw(im) mp = hashlib.md5() mp.update(str(datetime.datetime.now())) mp_src = mp.hexdigest() rand_str = mp_src[0:4] draw.text((30, 0), rand_str[0], font=ImageFont.truetype("/usr/workspace/news/static/DejaVuSans-Bold.ttf", random.randrange(70, 110))) draw.text((78, 0), rand_str[1], font=ImageFont.truetype("/usr/workspace/news/static/DejaVuSans-Bold.ttf", random.randrange(70, 110))) draw.text((135, 0), rand_str[2], font=ImageFont.truetype("/usr/workspace/news/static/DejaVuSans-Bold.ttf", random.randrange(70, 110))) draw.text((185, 0), rand_str[3], font=ImageFont.truetype("/usr/workspace/news/static/DejaVuSans-Bold.ttf", random.randrange(70, 110))) del draw request.session['checkcode'] = rand_str buf = cStringIO.StringIO() im.save(buf, 'png') session = db.db_createSession() print token_id token = session.query(Token).filter(Token.token_id == token_id).all() if len(token) == 1: print rand_str token[0].code_id = rand_str session.add(token[0]) session.commit() session.close() return HttpResponse(buf.getvalue(), 'image/png')
def main(): # Display resolution in epd2in13.py EPD_WIDTH = 128 EPD_HEIGHT = 250 # For simplicity, the arguments are explicit numerical coordinates # image = Image.new('1', (epd2in13.EPD_WIDTH, epd2in13.EPD_HEIGHT), 255) # 255: clear the frame image = Image.new('1', (EPD_HEIGHT, EPD_WIDTH), 255) # 255: clear the frame draw = ImageDraw.Draw(image) #Screen is horizontal #the TOP LEFT (sticker) angle is 0,0, BOTTOM RIGHT is max image_width, image_height = image.size w = ["unknown", 0, 0] font24 = ImageFont.truetype('DisposableDroidBB.ttf', 24) font16 = ImageFont.truetype('DisposableDroidBB.ttf', 16) try: pass #w = getWeather (0) #0 = today, 1 = tomorrow, ... except BaseException,ex: #something wrong happened print (ex) pass
def __init__(self): self.font_tahoma_blk_18 = ImageFont.truetype("tahomabd.ttf", 18) self.font_tahoma_blk_13 = ImageFont.truetype("tahomabd.ttf", 14) self.font_tahoma_12 = ImageFont.truetype("tahoma.ttf", 13) self.font_tahoma_10 = ImageFont.truetype("tahoma.ttf", 12) # self.font_arial_blk_13 = ImageFont.truetype("ariblk.ttf", 13) # self.font_arial_12 = ImageFont.truetype("arial.ttf", 12) # self.font_arial_10 = ImageFont.truetype("arial.ttf", 10) self.line_spacing = 2 self.padding = 30 self.min_width = 50 self.min_height = 50 self.font_map = [self.font_tahoma_blk_13, self.font_tahoma_12, self.font_tahoma_12, self.font_tahoma_12] self.text = None self.color = (50,50,100) self.transparency = 170 self.status = [] self.height = 50 self.width = 200 self.min_width = 200 self.sprite = None self.max_width = 325
def draw_to_PIL(self, canvas, width, height): center = [width/2, height/2] x = center[0] + self.x y = center[1] + self.y if self.selected: canvas.ellipse((x-self.size-3, y-self.size-3, x+self.size+3, y+self.size+3), fill="cyan") try: if self.color=="#ffffff" or self.color=="white": canvas.ellipse((x-self.size-1, y-self.size-1, x+self.size+1, y+self.size+1), fill="black") canvas.ellipse((x-self.size, y-self.size, x+self.size, y+self.size), fill=self.color) except: self.color="red" self.size=5 canvas.ellipse((x-self.size, y-self.size, x+self.size, y+self.size), fill=self.color) if self.label!="NULL": try: fontdir = os.path.join(os.environ["windir"], "fonts") font=ImageFont.truetype(os.path.join(fontdir,u'ARIALBD.TTF'),self.lsize) except: fontdir = "/Library/Fonts" font=ImageFont.truetype(os.path.join(fontdir,u'Arial Bold.ttf'),self.lsize) try: canvas.text((x+self.lx, y+self.ly-8), text=str(self.label), font=font, fill=self.lcolor) except: self.lx=-12 self.ly=-12 self.lcolor="magenta" self.lsize=16 canvas.text((x+self.lx, y+self.ly-8), text=str(self.label), font=font, fill=self.lcolor) return canvas
def get_font(font_path, font_size): try: font = ImageFont.truetype(font_path, font_size) except IOError: font = ImageFont.load_default() return font
def __init__(self, parent, chrt, options, mainfr, id = -1, size = wx.DefaultSize): commonwnd.CommonWnd.__init__(self, parent, chrt, options, id, size) self.mainfr = mainfr self.FONT_SIZE = int(21*self.options.tablesize) #Change fontsize to change the size of the table! self.SPACE = self.FONT_SIZE/2 self.LINE_HEIGHT = (self.SPACE+self.FONT_SIZE+self.SPACE) #essentials self.LINE_NUM = 23 self.COLUMN_NUM = 7# +leftmost +degreewins self.SMALL_CELL_WIDTH = 5*self.FONT_SIZE self.LONGITUDE_CELL_WIDTH = 7*self.FONT_SIZE self.CELL_WIDTH = 7*self.FONT_SIZE self.DEGREEWINS_CELL_WIDTH = 7*self.FONT_SIZE self.TITLE_HEIGHT = self.LINE_HEIGHT self.TITLE_WIDTH = 10*self.FONT_SIZE self.TABLE_WIDTH = (self.SMALL_CELL_WIDTH+self.LONGITUDE_CELL_WIDTH+(self.COLUMN_NUM)*(self.CELL_WIDTH)+self.DEGREEWINS_CELL_WIDTH) self.TABLE_HEIGHT = (self.TITLE_HEIGHT+self.LINE_NUM*self.LINE_HEIGHT) self.HEIGHT = (commonwnd.CommonWnd.BORDER+self.TABLE_HEIGHT+commonwnd.CommonWnd.BORDER) self.WIDTH = (commonwnd.CommonWnd.BORDER+self.TABLE_WIDTH+commonwnd.CommonWnd.BORDER) self.SetVirtualSize((self.WIDTH, self.HEIGHT)) self.fntMorinus = ImageFont.truetype(common.common.symbols, self.FONT_SIZE) self.fntText = ImageFont.truetype(common.common.abc, self.FONT_SIZE) self.clrs = (self.options.clrdomicil, self.options.clrexal, self.options.clrperegrin, self.options.clrcasus, self.options.clrexil) self.signs = common.common.Signs1 if not self.options.signs: self.signs = common.common.Signs2 self.deg_symbol = u'\u00b0' self.drawBkg()
def printOutputs(outputs): #initialize canvas = Image.new("RGB", (330,3350), (255,255,255)) step = 80 row = 1 font = ImageFont.truetype("Arial.ttf",10) draw = ImageDraw.Draw(canvas) #print header headerFont = ImageFont.truetype("Arial.ttf",15) draw.text((20,30),"Image",font=headerFont, fill=(0,0,0)) draw.text((120,30),"Best Match",font=headerFont, fill=(0,0,0)) draw.text((220,30),"Worst Match",font=headerFont, fill=(0,0,0)) #print images for output in outputs: imageNum = output[0] bestImageNum = output[1] worstImageNum = output[2] image = Image.open(helper_functions.image_path(imageNum)) bestImage = Image.open(helper_functions.image_path(bestImageNum)) worstImage = Image.open(helper_functions.image_path(worstImageNum)) canvas.paste(image,(10,row*step,99,row*step+60)) canvas.paste(bestImage,(110,row*step,199,row*step+60)) canvas.paste(worstImage,(210,row*step,299,row*step+60)) draw.text((20,row*step+63),"Image: " + str(imageNum),font=font, fill=(0,0,0)) draw.text((120,row*step+63),"Image: " + str(bestImageNum),font=font, fill=(0,0,0)) draw.text((220,row*step+63),"Image: " + str(worstImageNum),font=font, fill=(0,0,0)) row += 1 canvas.save("Part3Output.jpg", "JPEG")
def _create_win(self): try: key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts') except EnvironmentError: try: key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Fonts') except EnvironmentError: raise FontNotFound('Can\'t open Windows font registry key') try: path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True) self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size) for style in ('ITALIC', 'BOLD', 'BOLDITALIC'): path = self._lookup_win(key, self.font_name, STYLES[style]) if path: self.fonts[style] = ImageFont.truetype(path, self.font_size) else: if style == 'BOLDITALIC': self.fonts[style] = self.fonts['BOLD'] else: self.fonts[style] = self.fonts['NORMAL'] finally: _winreg.CloseKey(key)
def captcha_image(request,key): store = get_object_or_404(CaptchaStore,hashkey=key) text=store.challenge tmpimage = Image.new('RGB', (10,10), settings.CAPTCHA_BACKGROUND_COLOR) if settings.CAPTCHA_FONT_PATH.lower().strip().endswith('ttf'): font = ImageFont.truetype(settings.CAPTCHA_FONT_PATH,settings.CAPTCHA_FONT_SIZE) else: font = ImageFont.load(settings.CAPTCHA_FONT_PATH) tmpdraw = ImageDraw.Draw(tmpimage) size = tmpdraw.textsize(text, font=font) image = tmpimage.resize((size[0]+4,size[1]+4)) del(tmpimage,tmpdraw) draw = ImageDraw.Draw(image) draw.text((2, 2), text, font = font, fill = settings.CAPTCHA_FOREGROUND_COLOR) for f in settings.noise_functions(): draw = f(draw,image) for f in settings.filter_functions(): image = f(image) out = StringIO() image.save(out,"PNG") out.seek(0) response = HttpResponse() response['Content-Type'] = 'image/png' response.write(out.read()) return response
def stroop(arg, clr, side = "Left"): global config, speed fontSize = 108 font = ImageFont.truetype(config.path + '/fonts/freefont/FreeSansBold.ttf', fontSize) font2 = ImageFont.truetype(config.path + '/fonts/freefont/FreeSansBold.ttf', fontSize) pixLen = config.draw.textsize(arg, font = font) yOffset = int((pixLen[1] - 26)/4) image = Image.new("RGBA", pixLen) draw = ImageDraw.Draw(image) clr = tuple(int(a*config.brightness) for a in (clr)) # If not passed in, make the background the "opposite" color - from the seqs directory oppClr = config.colorCompliment(clr) draw.rectangle((0,0,image.size[0], max(32,pixLen[1])), fill=oppClr) # fudged shadow draw.text((-1,-1-yOffset),arg,(0,0,0),font=font2) draw.text((1,1-yOffset),arg,(0,0,0),font=font2) draw.text((0,-yOffset),arg,clr,font=font) #config.matrix.Clear() start = 0 if (side == "Right") : start = config.screenWidth/2 motions.append([image,0,side,start, config.stroopSteps])
def get(self): font1 = ImageFont.truetype(os.path.join(self.settings['static_path'], 'font/Sketchetik-Light.ttf'), random.randint(20, 28)) font2 = ImageFont.truetype(os.path.join(self.settings['static_path'], 'font/Sketchetik-Light.ttf'), random.randint(20, 28)) font3 = ImageFont.truetype(os.path.join(self.settings['static_path'], 'font/Sketchetik-Light.ttf'), random.randint(20, 28)) font4 = ImageFont.truetype(os.path.join(self.settings['static_path'], 'font/Sketchetik-Light.ttf'), random.randint(20, 28)) color_choices = ["#cccccc", "#666666", "#999999", "#111111", "#000000", "#aaaaaa"] font1_color = random.choice(color_choices) font2_color = random.choice(color_choices) font3_color = random.choice(color_choices) font4_color = random.choice(color_choices) im = Image.new('RGBA',(80, 30), random.choice(["#eeeeee", "#fffddd", "#eeefff", "#ededed"])) draw = ImageDraw.Draw(im) rands = random.sample("abcdefghijkmnpqrstuvwxyz23456789", 4) rands_str = ''.join(rands) self.session["regist_verify"] = rands_str self.session.save() font1_left = random.randint(5, 13) font2_left = random.randint(27, 33) font3_left = random.randint(47, 53) font4_left = random.randint(63, 70) draw.text((font1_left, random.randint(0, 5)), rands[0], font=font1, fill=font1_color) draw.text((font2_left, random.randint(0, 5)), rands[1], font=font2, fill=font2_color) draw.text((font3_left, random.randint(0, 5)), rands[2], font=font3, fill=font3_color) draw.text((font4_left, random.randint(0, 5)), rands[3], font=font4, fill=font4_color) del draw buf = cStringIO.StringIO() im.save(buf, 'png') self.write(buf.getvalue()) self.set_header(name="Content-Type", value="image/png") self.set_header(name="Content-Disposition", value="attachment;filename=%s.png" %getMd5('regist_verify')) self.flush()
def rect_text(self, image, rect, text): """ Allows to draw text in an rectangle area *image* - Image instance *rect* - the 4-tuple that defines a region, where coordinates are (left, upper, right, lower) *text* - a string to draw it in the box Font size will be calculated automaticly """ draw = ImageDraw.Draw(image) font_size = 1 f = ImageFont.truetype(self.font_file, font_size) width = rect[2] - rect[0] height = rect[3] - rect[1] while f.getsize(text)[0] < width and f.getsize(text)[1] < height: font_size += 1 f = ImageFont.truetype(self.font_file, font_size) if f.getsize(text)[0] > width or f.getsize(text)[1] > height: font_size -= 1 f = ImageFont.truetype(self.font_file, font_size) x = rect[0] + (width - f.getsize(text)[0]) / 2 y = rect[1] + (height - f.getsize(text)[1]) / 2 if self.use_shadow: self.draw_shadow(draw, f, text, x, y) draw.text((x, y), text, font=f, fill=self.font_color) del draw
def _get_font(self, font_type, size, typeface): """Get font with given parameters.""" font_path = helpers.get_font_path(font_type, typeface) if font_path: return ImageFont.truetype(font_path, helpers.pt_to_px(size)) return ImageFont.load_default()
def captcha_image(request, key): store = get_object_or_404(CaptchaStore, hashkey=key) text = store.challenge if settings.CAPTCHA_FONT_PATH.lower().strip().endswith('ttf'): font = ImageFont.truetype(settings.CAPTCHA_FONT_PATH, settings.CAPTCHA_FONT_SIZE) else: font = ImageFont.load(settings.CAPTCHA_FONT_PATH) size = font.getsize(text) size = (size[0] * 2, int(size[1] * 1.2)) image = Image.new('RGB', size, settings.CAPTCHA_BACKGROUND_COLOR) try: PIL_VERSION = int(NON_DIGITS_RX.sub('', Image.VERSION)) except: PIL_VERSION = 116 xpos = 2 charlist = [] for char in text: if char in settings.CAPTCHA_PUNCTUATION and len(charlist) >= 1: charlist[-1] += char else: charlist.append(char) for char in charlist: fgimage = Image.new('RGB', size, settings.CAPTCHA_FOREGROUND_COLOR) charimage = Image.new('L', font.getsize(' %s ' % char), '#000000') chardraw = ImageDraw.Draw(charimage) chardraw.text((0, 0), ' %s ' % char, font=font, fill='#ffffff') if settings.CAPTCHA_LETTER_ROTATION: if PIL_VERSION >= 116: charimage = charimage.rotate(random.randrange(*settings.CAPTCHA_LETTER_ROTATION), expand=0, resample=Image.BICUBIC) else: charimage = charimage.rotate(random.randrange(*settings.CAPTCHA_LETTER_ROTATION), resample=Image.BICUBIC) charimage = charimage.crop(charimage.getbbox()) maskimage = Image.new('L', size) maskimage.paste(charimage, (xpos, 4, xpos + charimage.size[0], 4 + charimage.size[1])) size = maskimage.size image = Image.composite(fgimage, image, maskimage) xpos = xpos + 2 + charimage.size[0] image = image.crop((0, 0, xpos + 1, size[1])) draw = ImageDraw.Draw(image) for f in settings.noise_functions(): draw = f(draw, image) for f in settings.filter_functions(): image = f(image) out = StringIO() image.save(out, "PNG") out.seek(0) response = HttpResponse() response['Content-Type'] = 'image/png' response.write(out.read()) return response
def plot_sparkline_smooth(results, args): step = int(args.get('step', '2')) height = int(args.get('height', '20')) width_base = (len(results)-1)*step width = width_base + len(str(max(results)))*8 (dmin, dmax) = [int(x) for x in args.get('limits', '0,100').split(',')] im = Image.new("RGB", (width, height), args.get('bgcolor', '#f2f2f2')) draw = ImageDraw.Draw(im) coords = zip(range(1,len(results)*step+1, step), [height - 3 - (y-dmin)/(float(dmax - dmin +1)/(height-4)) for y in results]) draw.line(coords, fill="#888888") min_color = args.get('min-color', '#0000FF') max_color = args.get('max-color', '#00FF00') last_color = args.get('last-color', '#FF0000') has_min = args.get('min-m', 'false') has_max = args.get('max-m', 'false') has_last = args.get('last-m', 'false') if has_min == 'true': min_pt = coords[results.index(min(results))] draw.rectangle([min_pt[0]-1, min_pt[1]-1, min_pt[0]+1, min_pt[1]+1], fill=min_color) if has_max == 'true': max_pt = coords[results.index(max(results))] draw.rectangle([max_pt[0]-1, max_pt[1]-1, max_pt[0]+1, max_pt[1]+1], fill=max_color) if has_last == 'true': end = coords[-1] draw.rectangle([end[0]-1, end[1]-1, end[0]+1, end[1]+1], fill=last_color) draw.text([width_base + 4, 1], str(max(results)), font=ImageFont.truetype('04b03.ttf', 8), fill=(0,0,0,0)) draw.text([width_base + 4, 11], str(min(results)), font=ImageFont.truetype('04b03.ttf', 8), fill=(0,0,0,0)) del draw f = StringIO.StringIO() im.save(f, "PNG") return f.getvalue()
def generateImage(price, currency, color): """Generate an Image object. price is a float, and currency is a three letter string to be shown after the price (e.g., 'BTC'). To try to get better looking images, the original image is 4x larger and it is scaled down with antialiasing. """ price_str = '{0:.4f} {1}'.format(price, currency) w, h = int(len(price_str) * 30 + 16), 56 img = Image.new('RGBA', (w, h), (255, 255, 255, 0)) draw = ImageDraw.Draw(img) try: font = ImageFont.truetype(FONT_PATH, 50) except: font = ImageFont.load_default() draw.text((0, 0), price_str, font=font, fill=color) img = img.resize((w/4, h/4), Image.ANTIALIAS) return img
def display_time(): # Collect current time and date if(time_format): current_time = time.strftime("%I:%M") else: current_time = time.strftime("%H:%M") current_date = time.strftime("%d/%m/%Y") # Clear image buffer by drawing a black filled box draw.rectangle((0,0,width,height), outline=0, fill=0) # Set font type and size font = ImageFont.truetype('Minecraftia.ttf', 35) # Position time x_pos = (disp.width/2)-(string_width(font,current_time)/2) y_pos = 2 + (disp.height-4-8)/2 - (35/2) # Draw time draw.text((x_pos, y_pos), current_time, font=font, fill=255) # Set font type and size font = ImageFont.truetype('Minecraftia.ttf', 8) # Position date x_pos = (disp.width/2)-(string_width(font,current_date)/2) y_pos = disp.height-10 # Draw date draw.text((x_pos, y_pos), current_date, font=font, fill=255) # Draw the image buffer disp.image(image) disp.display()
def change_value(self, name, value): if name == "font_face": if type(value) in (str, unicode): return sizes = [] import ImageFont fontname = value.GetFaceName() filename = self.get_font_filename(value) if not filename and wx.Platform == "__WXMAC__": filename = "/Library/Fonts/" + fontname + "/rsrc" if filename[-4:].upper() in ('.TTF', '.OTF',) or filename[-6:].upper() == '.DFONT' or filename.endswith("/rsrc"): font = ImageFont.truetype(filename, value.GetPointSize()) else: font = ImageFont.load(filename, value.GetPointSize()) total_width = 0 max_height = 0 for c in self.obj.letters: size = font.getsize(c) max_height = max(max_height, size[1]) total_width += size[0] sizes.append(size[0]) self.resource.sync() self.build_font_image(fontname, font, (total_width, max_height), False) PropertiesBarChangeValue(self.resource, self.obj, "font_face", (("widths", tuple(sizes)), ("filename", join("fonts", str(fontname) + '.png')), ("font_face", fontname)), multiple = True, update_now = True) elif name in ("color", "scale", "alpha"): setattr(self.mouquet.sprite, name, value) AdvancedCompanion.change_value(self, name, value) else: AdvancedCompanion.change_value(self, name, value)
def label2img(labellist, height, fontname="helvR08.pil", imgformat="PNG", fgcolor=(0,0,0), bgcolor=(255,255,255), rotate_angle=0): if exists(os.path.join(fontpath,fontname)): font = ImageFont.load(os.path.join(fontpath,fontname)) else: font = ImageFont.load_default() imgOut = Image.new("RGBA", (20,49), bgcolor) # calculate space needed to render text draw = ImageDraw.Draw(imgOut) sizex, sizey = draw.textsize(labellist[0], font=font) labelNum=len(labellist) imgOut = imgOut.resize((sizex,height*labelNum)) draw = ImageDraw.Draw(imgOut) # render label into image draw area for i in range(labelNum): draw.text((0, i*height), labellist[i], fill=fgcolor, font=font) if rotate_angle: imgOut = imgOut.rotate(rotate_angle) return imgOut
def __init__(self, parent, chrt, options, mainfr, id = -1, size = wx.DefaultSize): commonwnd.CommonWnd.__init__(self, parent, chrt, options, id, size) self.mainfr = mainfr self.FONT_SIZE = int(21*self.options.tablesize) #Change fontsize to change the size of the table! self.SPACE = self.FONT_SIZE/2 self.LINE_HEIGHT = (self.SPACE+self.FONT_SIZE+self.SPACE) self.LINE_NUM = len(self.chart.asteroids.asteroids) self.COLUMN_NUM = 4 self.CELL_WIDTH = 8*self.FONT_SIZE self.TITLE_HEIGHT = self.LINE_HEIGHT self.TITLE_WIDTH = self.COLUMN_NUM*self.CELL_WIDTH self.SPACE_TITLEY = 0 self.TABLE_HEIGHT = (self.TITLE_HEIGHT+self.SPACE_TITLEY+(self.LINE_NUM)*(self.LINE_HEIGHT)) self.TABLE_WIDTH = (self.CELL_WIDTH+self.COLUMN_NUM*self.CELL_WIDTH) self.WIDTH = (commonwnd.CommonWnd.BORDER+self.TABLE_WIDTH+commonwnd.CommonWnd.BORDER) self.HEIGHT = (commonwnd.CommonWnd.BORDER+self.TABLE_HEIGHT+commonwnd.CommonWnd.BORDER) self.SetVirtualSize((self.WIDTH, self.HEIGHT)) self.fntMorinus = ImageFont.truetype(common.common.symbols, self.FONT_SIZE) self.fntText = ImageFont.truetype(common.common.abc, self.FONT_SIZE) self.signs = common.common.Signs1 if not self.options.signs: self.signs = common.common.Signs2 self.deg_symbol = u'\u00b0' self.drawBkg()
def waterMark(img_src, user_name, page_url): logo = Image.open(LOGO_SRC) #原始图片 im = Image.open(img_src) #原始图片 (im_width, im_height) = im.size if im.format != 'GIF' and im_width > 320: (logo_width, logo_height) = logo.size if im.mode != 'RGBA': im = im.convert('RGBA') if logo.mode != 'RGBA': logo = logo.convert('RGBA') font = ImageFont.truetype(FONT, FONT_SIZE) #设置字体及文字尺寸 en_font = ImageFont.truetype(FONT, FONT_SIZE) #设置字体及文字尺寸 #链接水印 (url_width, url_height) = en_font.getsize(page_url) #获得文字水印的尺寸 url_mark = Image.new("RGBA", (url_width, url_height)) #创建水印透明背景图 draw = ImageDraw.ImageDraw(url_mark, "RGBA") #绘制水印透明背景图 draw.text((0,0), page_url, font=en_font, fill=FONT_COLOR) mark_pos = (im_width-url_width-MARGIN-logo_width, im_height-url_height-PADDING) im.paste(url_mark, mark_pos, url_mark) #用户名水印 (name_width, name_height) = font.getsize(user_name) #获得文字水印的尺寸 name_mark = Image.new("RGBA", (name_width, name_height)) #创建水印透明背景图 draw = ImageDraw.ImageDraw(name_mark, "RGBA") #绘制水印透明背景图 draw.text((0,0), user_name, font=font, fill=FONT_COLOR) name_pos = (im_width-name_width-MARGIN-logo_width, im_height-url_height-name_height-PADDING) im.paste(name_mark, name_pos, name_mark) #logo水印 logo_pos = (im_width-logo_width-PADDING+2, im_height-logo_height-PADDING) im.paste(logo, logo_pos, logo) im.save(img_src)
def set_bay_numbers(arg, d, sx, sy): x = sx + 8.5*s yt = sy + 4*s yb = yt + (h - 14)*s limit = int((d-4)/2) #if(limit % 2 == 0): #limit += 1 for i in range (0, limit): #error(i) st = str(i) if( len(st) == 1): z = x + .75*s else: z = x if(arg[i] != "O"): if(i % 2 == 0): draw.text((z,yb ), arg[i], (0,0,0), font=font) f = ImageFont.truetype("../TextFormats/FreeMonoOblique.ttf", 12) draw.text((z,yb + 2.5*s ), "Tail", (0,0,0), font=f) else: draw.text((z,yt ), arg[i], (0,0,0), font=font) f = ImageFont.truetype("../TextFormats/FreeMonoOblique.ttf", 12) draw.text((z,yt + 2.5*s ), "Head", (0,0,0), font=f) x += 10*s
def drawData(imagex, imagey, gapx, gapy, cellx, celly, cells, cellshape, bgcolor, bdexist, bdcolor, printval): global dataset if exists(os.path.join(fontpath,"courR08.pil")): font = ImageFont.load(os.path.join(fontpath,"courR08.pil")) else: font = ImageFont.load_default() dataimg = Image.new("RGBA", (imagex,imagey), bgcolor) draw = ImageDraw.Draw(dataimg) for i in range(0,imagex,gapx): for j in range(0,imagey,gapy): color=getColor(dataset[j/gapy][i/gapx]) x, y, z=color txcolor=(255-x, 255-y, 255-z) if cellshape == "rectangle": if bdexist == 'Y': draw.rectangle([i, j, i+cellx,j+celly], outline=bdcolor, fill=color) else: draw.rectangle([i, j, i+cellx,j+celly], fill=color) else: if bdexist == 'Y': draw.ellipse([i, j, i+cellx,j+celly], outline=bdcolor ,fill=color) else: draw.ellipse([i, j, i+cellx,j+celly], fill=color) if(printval=="Y"): draw.text((i+cells,j+cells), dataset[j/gapy][i/gapx], fill=txcolor, font=font) return dataimg
def create_demo_photo(self, picture_name): target_path = os.path.join(self._photo_path, picture_name) image_width = 1200 image_height = 800 # Choose random colors green_color_value = random.random() * 0.8 + 0.2 red_color_value = random.random() * 0.8 + 0.2 blue_color_value = random.random() * 0.8 + 0.2 image = Image.new("RGB", (image_width, image_height), 'black') draw = ImageDraw.Draw(image) # Draw gradient for x in range(image_width): for y in range(image_height): r = int(green_color_value * (x+1.0) / image_width * 255) g = int(red_color_value * (y+1.0) / image_height * 255) b = int(blue_color_value * (y+1.0) / (image_height + image_width / 2) * 255) color = (r, g, b) draw.point((x, y), fill=color) # Draw text try: font = ImageFont.truetype("ClientSideLib/OpenSans-Bold.ttf", 40) except IOError: font = ImageFont.load_default() draw.text(((image_width / 4), (image_height / 2 - 40)), picture_name, font=font) # Save image image.save(target_path, "JPEG")
def _drawBodySummaryOffert(im, data, rightTopCorner): global body_fontsize aprisXpos = 1700 fontSize = body_fontsize yStart = rightTopCorner[1]+16 fname = 'body' if len(data) == 1: _drawText(im, data[0].decode('UTF-8'), fontSize, (sizeA4[0]-body_xpadding, yStart), fonts[fname], True) return collumnsXStart = [aprisXpos, sizeA4[0]-body_xpadding] counter = 0 for line in data: if 'Summa inkl. moms:' in line: fontSize = 48 fname = 'header1' font = ImageFont.truetype(fonts[fname], fontSize) else: font = ImageFont.truetype(fonts[fname], fontSize) size = font.getsize(line) for collumn in line.decode('UTF-8').split('\t'): counter += 1 #print collumn + str(collumnsXStart[counter % 2]) _drawText(im, collumn, fontSize, (collumnsXStart[(counter % 2)-1], yStart), fonts[fname], True) yStart += size[1]+16
def __init__(self,name="Teste Mctesterton",kills=6432,wkills=534,dkills=140, deaths=3021, gold = False): self.gold = gold name = name.replace('_',' ') # Make Fonts self.yoster24 = ImageFont.truetype(KAG_DIR + 'frinkweb/stats/static/yoster.ttf',24) self.yoster12 = ImageFont.truetype(KAG_DIR + 'frinkweb/stats/static/yoster.ttf',12) # Load medal images self.loadImages() # Draw Medals medals = [] if kills >= 10: medals.append(self.drawMedals('All-Time',kills)) if wkills >= 10: medals.append(self.drawMedals('Weekly',wkills)) if dkills >= 10: medals.append(self.drawMedals('Today',dkills)) # Draw K/D insignia if deaths: insignia = self.drawInsignia(kills,deaths) else: insignia = Image.new("RGBA",(1,1),(0,0,0,0)) self.banner = self.assembleBanner(name,medals,insignia)
# Beaglebone Black software SPI config: # DC = 'P9_15' # RST = 'P9_12' # SCLK = 'P8_7' # DIN = 'P8_9' # CS = 'P8_11' # Hardware SPI usage: disp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000)) # Software SPI usage (defaults to bit-bang SPI interface): #disp = LCD.PCD8544(DC, RST, SCLK, DIN, CS) # Initialize library. font = ImageFont.truetype('/root/gpio/yahei.ttf', 10) disp.begin(contrast=60) # Clear display. disp.clear() disp.display() while True: if(lcdWidth==reset): lcdWidth=LCD.LCDWIDTH if(lcdWidth==stop_x): judge1=0 stop_time+=1 dec_x=0 if(stop_time==21): stop_time=0 judge1=1 #fcntl.flock(dec_x,fcntl.LOCK_EX)
def main(): global Debug_Mode Debug_Mode = 0 global do_screen_update do_screen_update = 1 global epd epd = epd7in5b.EPD() if Debug_Mode == 0: epd.init() else: print('-= Debug Mode =-') global todo_response todo_response = '' global cal_width cal_width = 240 global line_start line_start = 48 global weather_reponse global forecast_reponse # All fonts used in frames global font_cal font_cal = ImageFont.truetype( '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 16) global font_day font_day = ImageFont.truetype('fonts/Roboto-Black.ttf', 110) global font_weather font_weather = ImageFont.truetype('fonts/Roboto-Black.ttf', 20) global font_day_str font_day_str = ImageFont.truetype('fonts/Roboto-Light.ttf', 35) global font_month_str font_month_str = ImageFont.truetype('fonts/Roboto-Light.ttf', 25) global font_weather_icons font_weather_icons = ImageFont.truetype('fonts/meteocons-webfont.ttf', 45) global font_tasks_list_title font_tasks_list_title = ImageFont.truetype('fonts/Roboto-Light.ttf', 30) global font_tasks_list font_tasks_list = ImageFont.truetype('fonts/tahoma.ttf', 12) global font_tasks_due_date font_tasks_due_date = ImageFont.truetype('fonts/tahoma.ttf', 11) global font_tasks_priority font_tasks_priority = ImageFont.truetype('fonts/tahoma.ttf', 9) global font_update_moment font_update_moment = ImageFont.truetype('fonts/tahoma.ttf', 9) global icons_list icons_list = { u'01d': u'B', u'01n': u'C', u'02d': u'H', u'02n': u'I', u'03d': u'N', u'03n': u'N', u'04d': u'Y', u'04n': u'Y', u'09d': u'R', u'09n': u'R', u'10d': u'R', u'10n': u'R', u'11d': u'P', u'11n': u'P', u'13d': u'W', u'13n': u'W', u'50d': u'M', u'50n': u'W' } calendar.setfirstweekday(0) # Monday is the first day of the week global todo_wait todo_wait = 300 global refresh_time refresh_time = 900 start_time = time.time() + refresh_time while True: query_todo_list() if (do_screen_update == 1): do_screen_update = 0 refresh_Screen() start_time = time.time() + refresh_time elif (time.time() - start_time) > 0: print('-= General Refresh =-') refresh_Screen() start_time = time.time() + refresh_time time.sleep(todo_wait)
#!/usr/bin/python import epd7in5 import Image import ImageDraw import ImageFont from netifaces import interfaces, ifaddresses, AF_INET, AF_INET6 EPD_WIDTH = 640 EPD_HEIGHT = 384 epd = epd7in5.EPD() epd.init() image = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 1) draw = ImageDraw.Draw(image) head_text = ImageFont.truetype( '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', 28) body_text = ImageFont.truetype( '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24) text_y = 10 head_buffer = 10 line_height = 20 def print_line(text, style): global text_y y_pos = text_y text_y = text_y + line_height font = body_text if style == "heading": text_y = text_y + head_buffer + line_height
############################################################################## ############################################################################## # Start of main program ############################################################################## ############################################################################## # startup display disp=epd2in13b.EPD() disp.init() # image frames to be drawn frame_black = [0xFF] * (disp.width * disp.height / 8) frame_yellow = [0xFF] * (disp.width * disp.height / 8) # fonts to be used fontBold = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', 35) font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSans.ttf', 35) fontBoldBIG = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', 40) fontBIG = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSans.ttf', 40) # Get the weather data for the given location location_string = "{city}, {countrycode}".format(city=CITY, countrycode=COUNTRYCODE) weather = get_weather(location_string) # This maps the weather codes from the Yahoo weather API # to the appropriate weather icons icon_map = { "snow": [5, 6, 7, 13, 14, 15, 16, 17, 18, 41, 42, 43, 46], "rain": [8, 9, 10, 11, 12, 35, 40], "cloud": [19, 20, 21, 22, 25, 26, 27, 28, 44], "pcloud": [30, 44],
def getFont(self, size=18): font = self.fonts.get(size, ImageFont.truetype(self.fontFile, size)) self.fonts[size] = font return font
def rndChar(): return chr(random.randint(65, 90)) def rndColor(): return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) def rndColor2(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (255, 255, 255)) font = ImageFont.truetype('Arial.ttf', 36) draw = ImageDraw.Draw(image) for x in range(width): for y in range(height): draw.point((x, y), fill=rndColor()) for t in range(4): draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2()) image = image.filter(ImageFilter.BLUR) image.save('code.jpg', 'jpeg')
def generate(self, height=None, width=None, text=None, label=None): """ initialize the height and width of the user text block """ if not height: HEIGHT = self.HEIGHT else: HEIGHT = height if not width: WIDTH = self.WIDTH else: WIDTH = width # calculate the square of the user block in pixels self.BLOCK_SQUARE = WIDTH * HEIGHT BOX_W = self.BOX_W BORDER = self.BORDER qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=BOX_W, border=BORDER, ) # check the passed text if not text: text = self.TEXT # add the text to qr code qr.add_data(text) qr.make(fit=True) img = qr.make_image() pil_img = img._img img_w, img_h = pil_img.size # calculate the square of the whole image in pixels self.IMAGE_SQUARE = (img_h - BORDER * BOX_W) * (img_w - BORDER * BOX_W) # PIL Draw initial. draw = ImageDraw.Draw(pil_img) # quantity of all cubes(8*8px) in one line cubes = img_w / BOX_W left = (cubes / 2 - WIDTH / 2) * BOX_W top = (cubes / 2 - HEIGHT / 2) * BOX_W right = (cubes / 2 + WIDTH / 2) * BOX_W bottom = (cubes / 2 + HEIGHT / 2) * BOX_W draw.rectangle([left, top, right, bottom], fill=255) draw.rectangle([left, top, right, bottom]) if label: left_text = left + len(label) / 2 * BOX_W # text left offset top_text = top + HEIGHT / 3 * BOX_W # text top offset f = ImageFont.load_default() # font settings draw.text((left_text, top_text), label, font=f) # draw text pil_img.show() self.check_text(text) self.decode(pil_img)
@author: jim_byers python 2.7 """ import Image import requests from StringIO import StringIO import ImageFont import ImageDraw import textwrap import pandas as pd from sklearn.cluster import KMeans from datetime import datetime font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 35) output_path = "../image_output_files/" url = "https://raw.githubusercontent.com/JamesByers/Cluster-analysis-of-image-RGB-colors/master/image_input_files/Newport_seafood.png" ##import image from local file #input_path = "../image_input_files/" #img_filename = "Newport_seafood.png" #im = Image.open(input_path + img_filename) ##import image from a URL response = requests.get(url) im = Image.open(StringIO(response.content)) def placeText(image, a_str, font): # place center justified text on image font_color = (255, 165, 0)
# -*- coding: utf-8 -*- ''' 生成随机验证码 ''' import string strings = string.letters ascii_letters = string.ascii_letters import random import Image, ImageDraw, ImageFilter, ImageFont letter = '' myImg = Image.new('RGB', (100, 50), 'white') draw = ImageDraw.Draw(myImg) font = ImageFont.truetype("/usr/share/fonts/truetype/AbyssinicaSIL-R.ttf", 20) # for x in range(20): # for y in range(20): # draw.point((x*5,y*5), fill=(0,10,0)) # draw.line((x,y) + (myImg.size[1],myImg.size[0]), fill=20) for i in range(4): random_letter = random.choice(strings) print random_letter # letter += random_letter print draw.text((10 + i * 25, 18), str(random_letter), fill='red', font=font) myImg = myImg.filter(ImageFilter.MinFilter) myImg.save('hello.jpg', 'JPEG')
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Very basic tool to generate a binary font from a TTF. Currently # hardcodes a lot of things, so it's only really suitable for this demo. # # Assumes every glyph fits in an 8x8 box. Each glyph is encoded as # an uncompressed 8-byte bitmap, preceeded by a one-byte escapement. # import ImageFont, ImageDraw, Image FONT = "04B_03__.TTF" font = ImageFont.truetype(FONT, 8) glyphs = map(chr, range(ord(' '), ord('z') + 1)) print """/* * 8x8 variable-width binary font, AUTOMATICALLY GENERATED * by fontgen.py from %s */ static const uint8_t font_data[] = {""" % FONT for g in glyphs: width, height = font.getsize(g) assert width <= 8 assert height <= 8 im = Image.new("RGB", (8, 8)) draw = ImageDraw.Draw(im)
import ui, Image, ImageDraw, ImageFont, io from PIL import Image as ImageP # style = 'sheet' style = "fullscreen" font = ImageFont.truetype("Helvetica", 30) def Img2ui(ip): with io.BytesIO() as bIO: ip.save(bIO, "PNG") img = ui.Image.from_data(bIO.getvalue()) img = img.with_rendering_mode( ui.RENDERING_MODE_ORIGINAL ) # if you use ui.RENDERING_MODE_TEMPLATE your text is black return img class MyView(ui.View): def __init__(self): self.background_color = "lightgreen" self.draw_count = 0 self.layout_count = 0 def will_close(self): self.background_color = "lightgrey" print( "You can't see a lightgrey background, because the view is closed." )
def _paint_text(self, xpos, ypos): font = ImageFont.truetype(FONT, self.font_size * 2) width, height = font.getsize(self.text) pos = (mm2px(xpos, self.dpi) - width // 2, mm2px(ypos, self.dpi) - height // 4) self._draw.text(pos, self.text, font=font, fill=self.foreground)
# Initialize library disp.begin() # Get display width and height width = disp.width height = disp.height # Clear display disp.clear() disp.display() # Create image buffer with mode '1' for 1-bit color image = Image.new('1', (width, height)) # Load default font font = ImageFont.load_default() # Create drawing object draw = ImageDraw.Draw(image) prev_millis = 0 prev_social = 0 display = 0 time_format = True while True: millis = int(round(time.time() * 1000)) # Software debouncing if((millis - prev_millis) > 250): # Cycle through different displays
def multiple_avi(args): """ Generate avi from multiple cinefiles INPUT ----- args : Namespace object contain each of the arguments used to generate an avi. See the top of this file for details, or from a terminal cine2avi --help OUTPUT ----- None """ if args.timestamp: print(os.path.join(script_dir, 'Helvetica.ttf')) font = ImageFont.truetype(args.font, args.ts) files = args.cines #for i, fn in enumerate(files): fn = files[0].strip() frame_slice = slice(None) if '[' in fn: if fn[-1] == ']': fn, s = fn.split('[') try: frame_slice = slice(*map(noneint, s[:-1].split(':'))) except: raise ValueError("Couldn't convert '[%s' to slice notation" % s) else: print "Warning, found '[' in input, but it didn't end with ']', so I'll assume you didn't mean to give a frame range." base, ext = os.path.splitext(fn) ext = ext.lower() if not os.path.exists(fn): print "File %s not found, ignoring." % fn # continue output = args.output if '%s' in args.output: output = output % base elif '%' in args.output: output = output % i base, extout = os.path.splitext(output) output = output[:-6] + '_multiple' + extout print(output) bpp = None inp = [None for fn in files] if ext in ('.cin', '.cine'): inp_ref = cine.Cine(fn) for i, fn in enumerate(files): print(fn) fn = fn.strip() inp[i] = cine.Cine(fn) bpp = inp_ref.real_bpp if bpp < 8 or bpp > 16: bpp = None #Just in case td = args.td if args.td else int(ceil(log10(inp_ref.frame_rate))) t0 = 0. frame_text = lambda i: 't: %%.%df s, ' % td % (inp_ref.get_time( i) - t0) + 'Dt: %f ms' % (round( ((inp_ref.get_time(i) - inp_ref.get_time(i - 1)) * 1000) * 10) / 10) # 't: %f s \n Dt : ms' % elif ext in ('.tif', '.tiff'): inp = tiff.Tiff(fn) frame_text = lambda i: str(i) bpps = inp_ref[0].dtype.itemsize * 8 if bpp is None: bpp = bpps lengths = [len(i) for i in inp] print('Movie lengths :' + str(lengths)) Nmax = min(lengths) frames = range(*frame_slice.indices(Nmax)) if args.clip == 0: map = linspace(0., 2.**(bpps - bpp), 2**bpps) else: counts = 0 bins = arange(2**bpps + 1) for i in frames[::args.hist_skip]: c, b = histogram(inp_ref[i], bins) counts += c counts = counts.astype('d') / counts.sum() counts = counts.cumsum() bottom_clip = where(counts > args.clip)[0] if not len(bottom_clip): bottom_clip = 0 else: bottom_clip = bottom_clip[0] top_clip = where(counts < (1 - args.clip))[0] if not len(top_clip): top_clip = 2**bpps else: top_clip = top_clip[-1] #print bottom_clip, top_clip #import pylab #pylab.plot(counts) #pylab.show() #sys.exit() m = 1. / (top_clip - bottom_clip) map = clip(-m * bottom_clip + m * arange(2**bpps, dtype='f'), 0, 1) map = map**(1. / args.gamma) map = clip(map * 255, 0, 255).astype('u1') #print '%s -> %s' % (fn, output) ofn = output output = mjpeg.Avi(output, framerate=args.framerate, quality=args.quality) if args.rect is not None: rect = [int(i) for i in args.rect[1:-1].split(':')] print(rect) #print frames for i in StatusPrinter(frames, os.path.basename(ofn)): frame = [None for p in inp] for p, inpp in enumerate(inp): framep = inpp[i] if args.rotate: framep = rot90(framep, (args.rotate % 360) // 90) framep = map[framep] # print(type(frame)) if args.rect == None: frame[p] = asarray(framep) else: frame[p] = asarray(framep[rect[0]:rect[1], rect[2]:rect[3]]) fra = concatenate(tuple(frame), axis=0) if args.timestamp: fra = Image.fromarray(fra) draw = ImageDraw.Draw(fra) draw.text((args.tx, args.ty), frame_text(i), font=font, fill=args.tb) fra = asarray(fra) # print(type(frame)) # plt.imshow(fra) # plt.show() # input() output.add_frame(fra) output.close()
def __init__(self, clust_data, labels=None, bsize=10, tree_space=200): self.space = tree_space colours = [ 'blue', 'green', 'red', 'cyan', 'magenta', 'brown', 'orange' ] self.colour_map = self._init_colours( colours, [x.cluster_id for x in clust_data.datapoints]) if labels is None: labels = [ clust_data.datapoints[x].sample_id for x in clust_data.reorder_indices ] try: self.font = ImageFont.load( 'courR08.pil' ) #Copyright (c) 1987 Adobe Systems, Inc., Portions Copyright 1988 Digital Equipment Corp. except IOError: self.font = None if len(clust_data.consensus_matrix) != len(labels): raise ValueError, "Number of columns and column label arrays have different lengths!" Hmap.__init__(self, clust_data.consensus_matrix, bsize=bsize) #Creates image in self.im if HMAP_ENABLED if self.im is not None: old_draw = ImageDraw.Draw(self.im) self.max_textsize = 0 for label in labels: self.max_textsize = max( self.max_textsize, old_draw.textsize(label, font=self.font)[0]) del old_draw #Keep GC from keeping the old image around if clust_data.tree is None: self.space = self.max_textsize + 5 #Prepare newsize = (self.im.size[1] + self.space, self.im.size[0] ) #To hold our rotated copy and some text im = Image.new('RGBA', newsize, 'white') #Trick to make vertical text when we're done, and add tree space im.paste(self.im.rotate(-90), (0, 0, self.im.size[1], self.im.size[0])) self.im = im self.draw = ImageDraw.Draw(self.im) #Actual work self._add_cluster_labels(labels) if clust_data.tree is not None: self._draw_dendogram(clust_data.tree) #Finish self.im = self.im.rotate(90)
# coding: utf-8 import Image, ImageFont, ImageDraw image = Image.new("RGB", (200, 100)) draw = ImageDraw.Draw(image) # use a truetype font font = ImageFont.truetype("/usr/share/fonts/truetype/takao/TakaoExGothic.ttf", 32) draw.text((20, 32), u"あいうえお", font=font) image.save('foo.png', 'PNG')
def display(self): """ 生成并返回验证码图片 """ # 图片背景颜色 self.img_background = (random.randrange(230, 255), random.randrange(230, 255), random.randrange(230, 255)) # 生成图片 im = Image.new('RGB', (self.img_width, self.img_height), self.img_background) # 得到验证码 self.code = self._generate_verify_code() # 调整验证码字符大小 self.font_size = self._get_font_size() # 创建画笔 draw = ImageDraw.Draw(im) # 画随机干扰线,字数越少,干扰线越多 line_num = 4 for i in range(random.randrange(line_num - 2, line_num)): line_color = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)) xy = (random.randrange(0, int(self.img_width * 0.2)), random.randrange(0, self.img_height), random.randrange(3 * self.img_width / 4, self.img_width), random.randrange(0, self.img_height)) draw.line(xy, fill=line_color, width=int(self.font_size * 0.1)) # 写验证码 j = int(self.font_size * 0.3) k = int(self.font_size * 0.5) x = random.randrange(j, k) # 起始位置 for i in self.code: # 上下抖动量,字数越多,上下抖动越大 m = int(len(self.code)) y = random.randrange(1, 3) if i in ('+', '=', '?'): # 对计算符号等特殊字符放大处理 m = ceil(self.font_size * 0.8) else: # 字体大小变化量,字数越少,字体大小变化越多 m = random.randrange( 0, int(45 / self.font_size) + int(self.font_size / 5)) self.font = ImageFont.truetype(self.font_path.replace('\\', '/'), self.font_size + int(ceil(m))) draw.text((x, y), i, font=self.font, fill=random.choice(self.font_color)) x += self.font_size * 0.9 del x del draw buf = StringIO.StringIO() im.save(buf, 'gif') buf.closed return HttpResponse(buf.getvalue(), 'image/gif')
def __call__(self, args): try: os.makedirs(args.directory) except: pass since = None if args.since: since = parsedatetime.Calendar().parse(args.since) since = time.mktime(since[0]) since = datetime.datetime.fromtimestamp(since) if args.labels: font = ImageFont.truetype("arial.ttf", 14) else: font = None workers = session.query(turkic.models.Worker) for worker in workers: print "Sampling worker {0}".format(worker.id) jobs = session.query(Job) jobs = jobs.filter(Job.worker == worker) jobs = jobs.join(Segment) jobs = jobs.join(Video) jobs = jobs.filter(Video.isfortraining == False) if since: jobs = jobs.filter(turkic.models.HIT.timeonserver >= since) jobs = jobs.order_by(sqlalchemy.func.rand()) jobs = jobs.limit(args.number) for job in jobs: print "Visualizing HIT {0}".format(job.hitid) paths = [x.getboxes(interpolate = True, bind = True, label = True) for x in job.paths] if args.frames > job.segment.stop - job.segment.start: frames = range(job.segment.start, job.segment.stop + 1) else: frames = random.sample(xrange(job.segment.start, job.segment.stop + 1), args.frames) size = math.sqrt(len(frames)) video = job.segment.video bannersize = (video.width * int(math.floor(size)), video.height * int(math.ceil(size))) image = Image.new(video[0].mode, bannersize) size = int(math.floor(size)) offset = (0, 0) horcount = 0 paths = vision.visualize.highlight_paths(video, paths, font = font) for frame, framenum in paths: if framenum in frames: image.paste(frame, offset) horcount += 1 if horcount >= size: offset = (0, offset[1] + video.height) horcount = 0 else: offset = (offset[0] + video.width, offset[1]) image.save("{0}/{1}-{2}.jpg".format(args.directory, worker.id, job.hitid))
return files def get_avg_cmd_for_images(files, dest): cmd = 'convert ' + ' '.join(files) + ' -average ' + dest return cmd for hour in xrange(6, 21): for minute in xrange(0, 60): if hour == 6 and minute < 32: continue frames = get_frames_for_time(hour, minute) if len(frames) < 4: continue destfile = 'avg/%02i%02i.png' % (hour, minute) cmd = get_avg_cmd_for_images(frames, destfile) print cmd os.system(cmd) im = Image.open(destfile) font = ImageFont.truetype('Verdana', 12) draw = ImageDraw.Draw(im) draw.text((5, 5), '%02i:%02i' % (hour, minute), font=font) im.save(destfile)
def makeimage(infile, outfile, caption, tree, addcaption=True, dpi=1200, fontsize=14): if os.path.exists(outfile): os.remove(outfile) #print tree.get_midpoint_outgroup() #print tree.get_sisters() #print tree.get_tree_root() #root = tree.get_tree_root() #tree.delete( root ) #print "root", root #root.unroot() if print_ascii: print "redering tree", infile, "to", outfile, 'in ASCII' print tree.get_ascii() print tree.write() print "redering tree", infile, "to", outfile tree.render(outfile, dpi=dpi) if not os.path.exists(outfile): print "redering tree", infile, "to", outfile, 'FAILED' return None orig = Image.open(outfile) orig = makeColorTransparent(orig, transparent_color, thresh2=transparent_thresh) (orig_w, orig_h) = orig.size orig_dpi = orig.info["dpi"] print "ORIG width", orig_w, "height", orig_h, "dpi", orig_dpi charsperline = int(math.floor(orig_w / math.ceil(fontsize / 1.6))) textlines = [] if addcaption: print "charsperline", charsperline print "caption", caption for pos in xrange(0, len(caption), charsperline): #print "pos",pos,"end", pos+charsperline, caption[pos: pos+charsperline] textlines.append(caption[pos:pos + charsperline]) numlines = len(textlines) print "numlines", numlines htext = (fontsize * numlines) himgtext = orig_h + htext frame_w = int(orig_w * frame_prop) orig_w_frame = orig_w + (2 * frame_w) out = Image.new('RGBA', (orig_w_frame, himgtext), (255, 255, 255)) out.info["dpi"] = (dpi, dpi) maski = Image.new('L', (orig_w_frame, himgtext), color=255) mask = ImageDraw.Draw(maski) mask.rectangle((0, 0, orig_w_frame, himgtext), fill=0) out.putalpha(maski) out.paste(orig, (frame_w, 0)) if addcaption: fontname = 'Consolas.ttf' if os.path.exists(fontname): zoomout = 20 font = ImageFont.truetype(fontname, fontsize * zoomout) texti = Image.new("RGBA", (orig_w * zoomout, htext * zoomout)) text = ImageDraw.Draw(texti) for linepos in xrange(len(textlines)): hline = linepos * fontsize line = textlines[linepos] text.text((fontsize * zoomout, hline * zoomout), line, (0, 0, 0), font=font) texti = texti.resize((orig_w, htext), Image.ANTIALIAS) out.paste(texti, (frame_w, orig_h)) (out_w, out_h) = out.size out_dpi = out.info["dpi"] print "OUT width", out_w, "height", out_h, "dpi", out_dpi out.save(outfile, optimize=True, dpi=(dpi, dpi)) print "saved to %s" % outfile return
def display_text(self, pycon, position): self.draw_text_wrap(pycon["text"], position, 25, ImageFont.truetype('Montserrat-Regular.ttf', 22), fill=self.param["textcolor"])
def single_avi(args): if args.timestamp: print(os.path.join(script_dir, 'Helvetica.ttf')) font = ImageFont.truetype(args.font, args.ts) for i, fn in enumerate(args.cines): fn = fn.strip() frame_slice = slice(None) if '[' in fn: if fn[-1] == ']': fn, s = fn.split('[') try: frame_slice = slice(*map(noneint, s[:-1].split(':'))) except: raise ValueError( "Couldn't convert '[%s' to slice notation" % s) else: print "Warning, found '[' in input, but it didn't end with ']', so I'll assume you didn't mean to give a frame range." base, ext = os.path.splitext(fn) ext = ext.lower() if not os.path.exists(fn): print "File %s not found, ignoring." % fn continue output = args.output if '%s' in args.output: output = output % base elif '%' in args.output: output = output % i bpp = None if ext in ('.cin', '.cine'): inp = cine.Cine(fn) bpp = inp.real_bpp if bpp < 8 or bpp > 16: bpp = None #Just in case td = args.td if args.td else int(ceil(log10(inp.frame_rate))) # frame_text = lambda i: 't: %%.%df s' % td % (i/float(input.frame_rate)) # frame_text = lambda i: 't: %%.%d s' % (inp.get_time(i)) t0 = 0. frame_text = lambda i: 't: %%.%df s, ' % td % (inp.get_time( i) - t0) + 'Dt: %f ms' % (round( ((inp.get_time(i) - inp.get_time(i - 1)) * 1000) * 10) / 10 ) # 't: %f s \n Dt : ms' % elif ext in ('.tif', '.tiff'): inp = tiff.Tiff(fn) frame_text = lambda i: str(i) bpps = inp[0].dtype.itemsize * 8 if bpp is None: bpp = bpps frames = range(*frame_slice.indices(len(inp))) if args.clip == 0: map = linspace(0., 2.**(bpps - bpp), 2**bpps) else: counts = 0 bins = arange(2**bpps + 1) for i in frames[::args.hist_skip]: c, b = histogram(inp[i], bins) counts += c counts = counts.astype('d') / counts.sum() counts = counts.cumsum() bottom_clip = where(counts > args.clip)[0] if not len(bottom_clip): bottom_clip = 0 else: bottom_clip = bottom_clip[0] top_clip = where(counts < (1 - args.clip))[0] if not len(top_clip): top_clip = 2**bpps else: top_clip = top_clip[-1] #print bottom_clip, top_clip #import pylab #pylab.plot(counts) #pylab.show() #sys.exit() m = 1. / (top_clip - bottom_clip) map = clip(-m * bottom_clip + m * arange(2**bpps, dtype='f'), 0, 1) map = map**(1. / args.gamma) map = clip(map * 255, 0, 255).astype('u1') #print '%s -> %s' % (fn, output) ofn = output output = mjpeg.Avi(output, framerate=args.framerate, quality=args.quality) if args.rect is not None: rect = [int(i) for i in args.rect[1:-1].split(':')] print(rect) #print frames for i in StatusPrinter(frames, os.path.basename(ofn)): frame = inp[i] if args.rotate: frame = rot90(frame, (args.rotate % 360) // 90) frame = map[frame] # if args.rect == None: frame = asarray(frame) else: frame = asarray(frame[rect[0]:rect[1], rect[2]:rect[3]]) if args.timestamp: frame = Image.fromarray(frame) draw = ImageDraw.Draw(frame) draw.text((args.tx, args.ty), frame_text(i), font=font, fill=args.tb) frame = asarray(frame) # print(type(frame)) output.add_frame(frame) output.close()
#-*- coding: utf-8 -*- from __future__ import unicode_literals import Image import ImageDraw import time import ImageFont from rgbmatrix import Adafruit_RGBmatrix # Rows and chain length are both required parameters: matrix = Adafruit_RGBmatrix(32, 4) font = ImageFont.load_default() font = ImageFont.truetype("DejaVuSerif.ttf", size=10) img = Image.new('RGB', (128, 32)) d = ImageDraw.Draw(img) text = "Hellööå" d.text((1, 0), text, fill=(200, 200, 0), font=font) for n in range(128, -img.size[0], -1): # Scroll R to L matrix.SetImage(img.im.id, n, 0) time.sleep(0.025) matrix.SetImage(img.im.id, 0, 0) time.sleep(3)
def release(self): """ Release the gl resources for this Face. (This provides the functionality of KillFont () and font_data::clean () """ if (self.m_allocated): # Free up the glTextures and the display lists for our face glDeleteLists(self.m_list_base, 128) for ID in self.textures: glDeleteTextures(ID) # Extra defensive. Clients that continue to try and use this object # will now trigger exceptions. self.list_base = None self.m_allocated = False return def __del__(self): """ Python destructor for when no more refs to this Face object """ self.release() return # Unit Test harness if this python module is run directly. if __name__ == "__main__": print "testing availability of freetype font arial\n" ft = ImageFont.truetype("arial.ttf", 15) if ft: print "Found the TrueType font 'arial.ttf'" else: print "faild to find the TrueTYpe font 'arial'\n"
def __init__(self, width, height): Renderer.__init__(self, width, height) import Image, ImageDraw, ImageFont self._pil_image = Image.new("RGB", (width, height), (255, 255, 255)) self._draw = ImageDraw.Draw(self._pil_image, "RGB") self._pil_font = ImageFont.load_default()
draw.text((xoff + 1, yoff + 1), txt, fill=fgcolor, font=font) ht = 360 #720 ht = 360 #720 wd = 640 #1280 bgcolor = "#089931" #standard green image = Image.new("RGB", (wd, ht), bgcolor) draw = ImageDraw.Draw(image) fgcolor = "#f4fdf6" fontFile = "/usr/share/fonts/truetype/freefont/FreeSansBold.ttf" font = ImageFont.truetype(fontFile, 16) fontBig = ImageFont.truetype(fontFile, 20) txt1 = "THE FOLLOWING" txt2 = " PREVIEW " txt3 = "HAS BEEN APPROVED FOR" (x1, y1) = font.getsize(txt1) (x2, y2) = fontBig.getsize(txt2) (x3, y3) = font.getsize(txt3) addText(wd / 2 - (x1 + x2 + x3) / 2, 30, txt1, font, fgcolor) addTextBold(wd / 2 - (x1 + x2 + x3) / 2 + x1, 30 - 4, txt2, fontBig, fgcolor) addText(wd / 2 - (x1 + x2 + x3) / 2 + x1 + x2, 30, txt3, font, fgcolor) txt = "ALL AUDIENCES" (x, y) = fontBig.getsize(txt)
# John Zelle's graphics library... from graphics import * _tkCall = tkCall _tkExec = tkExec ver = "1.5" # only need to initialize the mixer -- other parts of pygame seem to # interfere with Tkinter on the Mac pygame.mixer.pre_init(22050, -16, False) _tkExec(pygame.mixer.init) try: if platform.system() == 'Darwin': defaultFont = ImageFont.truetype("/Library/Fonts/Times New Roman", 24) else: defaultFont = ImageFont.truetype("times.ttf", 24) except: defaultFont = ImageFont.load_default() # pygame.font.SysFont("times", 24) mediaFolder = user.home + os.sep print "Media Computation Library. Version " + str(ver) print "Started by Mark Guzdial" print "Updated by Nadeem Abdul Hamid, June 14 2007" def version(): global ver
def make_image(image, return_jpeg=True, plotlabel='', plotlabel2='', plotscale=False, **kwargs): """ Converts a data array to a color image using the Lupton scheme. This function takes a 3D array as input and returns a color image, either as a jpeg data stream or as a 3D array that can be shown with imshow. The image array must be ordered (x,y,band). Keyword arguments: return_jpeg -- if True, the function returns the jpeg data for the image as a string that can be written to a file, otherwise it returns a x*y*3 RGB array with range 0-1 that can be fed to matplotlib.imshow. band -- the slices of the input data used for the r,g,b channels. Should be either a tuple or a comma-separated string. scale -- specifies the scale of the input data. If a tuple or comma-separated string, specifies the image values in the three colors where saturation happens. Can also be set to "auto" or "autolum", in which case the values will be determined automatically based on the "autopercentile" keyword (see below). With "auto", each color is scaled independently to its max value, with "autolum" the scale is the same for all 3 channels so the overall color is preserved. autopercentile -- when autoscaling, sets the percentile of the pixels that will be saturated, i.e. for a value of 0.1, the scale value will be such that 10% of the pixels will be above it. While in principle the scale should be set by the brightest pixel, in practice this often doesn't work well because a few pixels are often much brighter than the rest. The stretch is set by the parameters alpha (default .3) and Q (default 9). Alpha sets the low-intensity scaling and Q sets the saturation behavior. Usage notes: While the default values of Q and alpha are mostly good, finding a good scaling value can be tricky. For the normal Sunrise outputs, which are surface brightness in lambda units, the scaling not only depends on how bright the object is in the selected bands, but also varies drastically with the wavelength of the bands due to the wavelength dependence of the units. On the other hand, because the images are in surface brightness, they are reflective of the real surface brightnesses of galaxies, so should be approximately independent of the simulation details as long as the galaxies are reasonably realistic. For the default urz images that are commonly shown in the Sunrise papers, the scaling values used are (1.5, 1, 1.5). A typical example of using this function to show an image with matplotlib would be (im is the image array): imshow(make_color.make_image(im, return_jpeg=False, band=(6,4,2), \ scale="autolum",autopercentile=0.1)) """ if kwargs.has_key("band"): band = kwargs["band"] else: band = (6, 4, 2) image = extract_bands(image, band) if kwargs.has_key("alpha"): alpha = float(kwargs["alpha"]) else: alpha = .3 if kwargs.has_key("Q"): Q = float(kwargs["Q"]) else: Q = 9 if kwargs.has_key("autopercentile"): autopercentile = kwargs["autopercentile"] else: autopercentile = 0.0005 m = 0 sz = image.shape slices = sz[0] xs = sz[1] ys = sz[2] # deal with nan image = where(image != image, 0, image) if kwargs.has_key("scale"): if kwargs["scale"] == "auto": # set scale scale = find_autoscale(image, autopercentile, lum=False) print "autoscaling:" #raise RuntimeError, `scale ` elif kwargs["scale"] == "autolum": scale = find_autoscale(image, autopercentile, lum=True) print "autoscaling:" elif isinstance(kwargs["scale"], str): sc = kwargs["scale"].split(',', 2) scale = (float(sc[0]), float(sc[1]), float(sc[2])) else: scale = kwargs["scale"] else: scale = (1., 1., 1.) print "scale", scale image *= array(scale) r = image[:, :, 0] g = image[:, :, 1] b = image[:, :, 2] i = (r + g + b) / 3 + 1e-20 r[:, :] = r * arcsinh(alpha * Q * (i - m)) / (Q * i) g[:, :] = g * arcsinh(alpha * Q * (i - m)) / (Q * i) b[:, :] = b * arcsinh(alpha * Q * (i - m)) / (Q * i) image = clip(image, 0.0, 1.0) if not return_jpeg: # imshow wants 0-1 range numbers, so that's what we return return image # the jpeg encoding wants 0-255 uchars image = image * 255 jpgimg = Image.fromarray(image.astype(uint8)) if plotlabel != '': #img = Image.open(img_fbase+'.jpg') draw = ImageDraw.Draw(jpgimg) # font = ImageFont.truetype(<font-file>, <font-size>) font = ImageFont.truetype( "/n/home00/lblecha/envs/MY_PYENV/fonts/DejaVuSans.ttf", 18) draw.text((15, 10), plotlabel, (255, 255, 255), font=font) if plotlabel2 != '': draw.text((15, 30), plotlabel2, (255, 255, 255), font=font) if plotscale: draw.line((25, 285, 55, 285), width=2) draw.text((15, 260), '5 kpc', font=font) jpg = jpgimg.tostring("jpeg", "RGB", 95) ### png encoder not enabled at install on odyssey #jpg = jpgimg.tostring("png","RGB", 95) return jpg
from ledwall import LedMatrix, ColorFader import sys import time import Image import ImageDraw import ImageFont matrix = LedMatrix() im = Image.new(mode="RGB", size=matrix.size) clean_data = list(im.getdata()) draw = ImageDraw.Draw(im) font = ImageFont.truetype("DejaVuSans.ttf", matrix.size[1]) draw.setfont(font) text = "<<</>>" if len(sys.argv) < 2 else sys.argv[1] image_width = matrix.size[0] text_width = draw.textsize(text)[0] width = text_width + image_width step = 0 colors = [(0xff, 0x00, 0x00), (0x00, 0xff, 0x00), (0x00, 0x00, 0xff)] fader = ColorFader(colors) while True:
import ImageDraw import ImageFont import epd2in13 epd = epd2in13.EPD() epd.init(epd.lut_full_update) font_base = '/home/pi/pynet/' else: from PIL import Image, ImageDraw, ImageFont font_base = './' test_file = 'sample-out.jpg' ping_host = 'google.com' ping_data = [0] * 50 # need data in list to start fail_count = 0 font_large = ImageFont.truetype(font_base + 'Roboto-Medium.ttf', 32) font_medium = ImageFont.truetype(font_base + 'runescape_uf.ttf', 16) print "Loaded Fonts" def newBlankImage(): image = Image.new('1', (image_width, image_height), 255) image = image.rotate(90, expand=1) draw = ImageDraw.Draw(image) return image, draw def write_image(image_to_draw, frames): if hostname == "raspberrypi": epd.clear_frame_memory(0xFF)