def set_font(self, family, size): Renderer.set_font(self, family, size) import ImageFont try: self._pil_font = ImageFont.load(family + ".ttf", size) except Exception: import warnings warnings.warn("Could not load %s.ttf font!", stacklevel=2) try: self._pil_font = ImageFont.load("cour.ttf", size) except Exception: warnings.warn("Could not load the cour.ttf font!! Loading the default", stacklevel=2) self._pil_font = ImageFont.load_default()
def set_font(self, family, size): Renderer.set_font(self, family, size) import ImageFont try: self._pil_font = ImageFont.load(family + ".ttf", size) except Exception: import warnings warnings.warn("Could not load %s.ttf font!", stacklevel=2) try: self._pil_font = ImageFont.load("cour.ttf", size) except Exception: warnings.warn( "Could not load the cour.ttf font!! Loading the default", stacklevel=2) self._pil_font = ImageFont.load_default()
def startUp(): log("Starting up ThexBerryClock (test)...") global TBC, iterations, itime iterations = 0 itime = int(time.time()) TBC = {} TBC['epoch'] = datetime.datetime.utcfromtimestamp(0) TBC['bhdisplay'] = 0 TBC['sleep'] = 0.01 TBC['clockmode'] = effect_startupSplash TBC['bitcoin'] = 0 TBC['btcopen'] = 0 TBC['rainbowBorderMode'] = 0 TBC['timers'] = {'bitcoin': 0, 'bhflipper': 0} TBC['timerFreqList'] = {'bitcoin': 60, 'bhflipper': 10} TBC['timerFuncList'] = { 'bitcoin': getBitcoinPrice, 'bhflipper': blockheight_flipDisplay } TBC['matrix'] = RGBMatrix(32, 2) TBC['matrix'].pwmBits = 11 TBC['matrix'].brightness = 50 TBC['canvas'] = TBC['matrix'].CreateFrameCanvas() TBC['font'] = ImageFont.load(basePath + "/pilfonts/timR08.pil") TBC['blockheight'] = 0 thread.start_new_thread(startup_blockheight, ()) signal.signal(signal.SIGUSR1, interruptHandler)
def __init__(self, size_x, size_y, display_q): super(DisplayThread, self).__init__() self.display_q = display_q self.bus = 0 self.device = 0 self.x_max = 128 self.y_max = 296 self.size_x = size_x self.size_y = size_y self.stoprequest = threading.Event() self.epd = epd2in9.EPD() self.epd.init(self.epd.lut_full_update) self.image = Image.new('1', (epd2in9.EPD_HEIGHT, epd2in9.EPD_WIDTH), 255) self.font = ImageFont.load('terminus_12.pil') self.line_height = 16 #self.font = ImageFont.truetype('terminus.ttf', 12) self.draw = ImageDraw.Draw(self.image) self.clear_display() self.clear_display() self.epd.init(self.epd.lut_partial_update) self.screen = pyte.Screen(self.size_x, self.size_y) self.stream = pyte.Stream(self.screen) self.buffer = [] self.cursor_enabled = False
def getImage(self, value, height=50, extension="PNG"): """ Get an image with PIL library value code barre value height height in pixel of the bar code extension image file extension""" import Image, ImageFont, ImageDraw from string import lower, upper # Create a missing font file decodeFontFile(courB08_pil, "courB08.pil") decodeFontFile(courB08_pbm, "courB08.pbm") # Get the bar code list bits = self.makeCode(value) # Get thee bar code with the checksum added code = "" for digit in self.EAN13: code += "%d" % digit # Create a new image position = 8 im = Image.new("1", (len(bits) + position, height)) # Load font font = ImageFont.load("courB08.pil") # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0, 0), (im.size[0], im.size[1])), fill=256) # Draw first part of number draw.text((0, height - 9), code[0], font=font, fill=0) # Draw first part of number draw.text((position + 7, height - 9), code[1:7], font=font, fill=0) # Draw second part of number draw.text((len(bits) / 2 + 6 + position, height - 9), code[7:], font=font, fill=0) # Draw the bar codes for bit in range(len(bits)): # Draw normal bar if bits[bit] == '1': draw.rectangle( ((bit + position, 0), (bit + position, height - 10)), fill=0) # Draw long bar elif bits[bit] == 'L': draw.rectangle( ((bit + position, 0), (bit + position, height - 3)), fill=0) # Save the result image im.save(code + "." + lower(extension), upper(extension))
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 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 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 startUp(): log("Starting up ThexBerryClock...") global TBC, iterations, itime iterations = 0 itime = int(time.time()) TBC = {} TBC['epoch']=datetime.datetime.utcfromtimestamp(0) TBC['bhdisplay'] = 0 TBC['sleep'] = 0.01 TBC['clockmode'] = effect_startupSplash TBC['bitcoin'] = 0 TBC['btcopen'] = 0 TBC['rainbowBorderMode'] = 0 TBC['timers'] = {'bitcoin':0,'bhflipper':0}; TBC['timerFreqList'] = {'bitcoin':60,'bhflipper':10}; TBC['timerFuncList'] = {'bitcoin':getBitcoinPrice,'bhflipper':blockheight_flipDisplay}; TBC['matrix'] = RGBMatrix(32, 2) TBC['matrix'].pwmBits = 11 TBC['matrix'].brightness = 50 TBC['canvas'] = TBC['matrix'].CreateFrameCanvas() TBC['font'] = ImageFont.load(basePath + "/pilfonts/timR08.pil") TBC['blockheight'] = 0 thread.start_new_thread( startup_blockheight, () ) signal.signal(signal.SIGUSR1, interruptHandler)
def Init(self, x, y, size = (10, 10), color = (255, 255, 255), light = [], medium = [], dark = [], textcolor = (0, 0, 0), font = '/fonts/helvB14.pil', linecolor = (0, 0, 0), backlinecolor = (150, 150, 150), mc = 1.1, devc = (1, 1), xres = 1, yres = 1, xname = '', yname = '', colormode='RGB'): # x and y self.__x = x self.__y = y # ymax self.__ymax = max(self.__y) # size self.__size = size # colormode self.__colormode = colormode # background color self.__color = color # colorlists self.__light = light self.__medium = medium self.__dark = dark # text color self.__textcolor = textcolor # font self.__font = ImageFont.load(font) # line color self.__linecolor = linecolor # background line color self.__backlinecolor = backlinecolor # mc if not (isinstance(mc, types.IntType) or isinstance(mc, types.FloatType)): raise error.Error, 'Der Overspill Koeffizient ist nicht korrekt angegeben!' self.__mc = mc # perspectivical deviation coefficient if not (isinstance(devc, types.TupleType) and (isinstance(devc[0], types.IntType) or isinstance(devc[0], types.FloatType)) and (isinstance(devc[1], types.IntType) or isinstance(devc[1], types.FloatType)) and len(devc) == 2 and devc[0] >= 0 and devc[1] >= 0): raise error.Error, 'Der Koeffizient fuer die perspektivische Abweichung ist nicht korrekt angegeben!' self.__devc = devc # unitnames if not isinstance(xname, types.StringType): raise error.Error, 'Der Name fuer die x-Argumente ist kein String!' self.__xname = xname if not isinstance(yname, types.StringType): raise error.Error, 'Der Name fuer die y-Argumente ist kein String!' self.__yname = yname # res if not (isinstance(xres, types.IntType) or isinstance(xres, types.FloatType)): raise Error, 'Die Darstellungsaufloesung fuer die x-Achse ist nicht in korrektem Format angegeben!' self.__xres = xres if not (isinstance(yres, types.IntType) or isinstance(yres, types.FloatType)): raise Error, 'Die Darstellungsaufloesung fuer die y-Achse ist nicht in korrektem Format angegeben!' self.__yres = yres
def drawBarCode(self, value, draw, x, y, height=30): """ Convert string value to bar code starting at (x,y) and draw onto a PIL image height specifies in pixel of the bar code """ import ImageFont # Get the bar code list bits = self.makeCode(value) # Get the bar code with the checksum added code = "" for digit in self.EAN13: code += "{n:d}".format(n=digit) # Load font font = ImageFont.load("courB08.pil") # Draw first part of number draw.text((x, y + height - 9), code[0], font=font, fill=0) # Draw first part of number draw.text((x + 15, y + height - 9), code[1:7], font=font, fill=0) # Draw second part of number draw.text((len(bits) / 2 + 14 + x, y + height - 9), code[7:], font=font, fill=0) # Draw the bar codes for bit in range(len(bits)): # Draw normal bar if bits[bit] == "1": draw.rectangle(((bit + x + 8, y), (bit + x + 8, y + height - 10)), fill=0) # Draw long bar elif bits[bit] == "L": draw.rectangle(((bit + x + 8, y), (bit + x + 8, y + height - 3)), fill=0)
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, "GIF") out.seek(0) response = HttpResponse() response['Content-Type'] = 'image/png' response.write(out.read()) return response
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 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 GetCode128C(inputdate): bits = "" checksum = 105 j = 1 for index, a in enumerate(inputdate): if (index % 2 == 0): checksum += int(inputdate[index:index + 2].rstrip()) * j if (int(inputdate[index:index + 2]) < 95): bits += str(int(inputdate[index:index + 2]) + 32) else: bits += str(int(inputdate[index:index + 2]) + 100) j += 1 index += 1 checksum = checksum % 103 if (checksum < 95): checksum += 32 else: checksum += 100 bits = str(205) + bits + str(checksum) + str(206) # Create a missing font file decodeFontFile(courB08_pil, "courB08.pil") decodeFontFile(courB08_pbm, "courB08.pbm") position = 8 im = Image.new("1", (len(bits) + position, 50)) # Load font font = ImageFont.load("courB08.pil") # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0, 0), (im.size[0], im.size[1])), fill=256) # Draw first part of number draw.text((0, 50 - 9), "hello", font=font, fill=0) # Draw first part of number draw.text((position + 7, 50 - 9), "hello", font=font, fill=0) # Draw second part of number draw.text((len(bits) / 2 + 6 + position, 50 - 9), "hello", font=font, fill=0) # Erase image draw.rectangle(((0, 0), (im.size[0], im.size[1])), fill=256) for bit in range(len(bits)): # Draw normal bar if bits[bit] == '1': draw.rectangle(((bit + position, 0), (bit + position, 50 - 10)), fill=0) # Draw long bar elif bits[bit] == 'L': draw.rectangle(((bit + position, 0), (bit + position, 50 - 3)), fill=0) # Save the result image im.save(inputdate + "." + lower("png"), upper("png"))
def apply(self, folder): if self["font"].reference(): for text in self: font = text["font"].pointer() font.prepare(folder) # Setup padding. padding = [ text["padleft"].get(), text["padright"].get(), text["padtop"].get(), text["padbottom"].get(), ] try: pad = self.number("padding") except rpl.RPLBadType: pad = self.list("padding") if len(pad) == 2: if padding[0] == "": padding[0] = pad[0].number() if padding[1] == "": padding[1] = pad[0].number() if padding[2] == "": padding[2] = pad[1].number() if padding[3] == "": padding[3] = pad[1].number() else: if padding[0] == "": padding[0] = pad[0].number() if padding[1] == "": padding[1] = pad[1].number() if padding[2] == "": padding[2] = pad[2].number() if padding[3] == "": padding[3] = pad[3].number() #endif else: if padding[0] == "": padding[0] = pad if padding[1] == "": padding[1] = pad if padding[2] == "": padding[2] = pad if padding[3] == "": padding[3] = pad #endtry font.render( self.rpl.share(text.resolve("file").get(folder), std.graphic.ImageFile), text.string(), { "box": [x.number() for x in text["box"].list()], "align": text["align"].string(), "valign": text["valign"].string(), "padleft": padding[0], "padright": padding[1], "padtop": padding[2], "padbottom": padding[3], "bg": text["bg"].tuple() } ) #endfor else: # Load a font file.. filename = self["font"].string() ext = os.path.splitext(filename)[1][1:].lower() try: self.font = ImageFont.load(filename) except IOError as err1: try: self.font = ImageFont.truetype(filename, self["size"].number()) except IOError as err2: raise RPLError("Could not load font %s, %s, %s." % (filename, err1.args[0], err2.args[0]))
def make_helvetica_centered_text(imageName, text, size=300, color=(0, 0, 0)): """ Draws the text on an image. If you have not downloaded the font, this function will probably crash. """ # Try loading the font my_font = ImageFont.load('C:/Python27/pilfonts/helvR24.pil') make_centered_text(imageName, text, size, my_font, color)
def getImagePIL(self, value, height = 50, extension = "PNG"): """ Get an image with PIL library value code barre value height height in pixel of the bar code extension image file extension. """ import Image, ImageFont, ImageDraw if len(value) != 12 and len(value) != 13: # Si no es de la longitud correcta para EAN13 genero un Code9 en EncapsulatedPostScript y # devuelvo un PIL con el contenido de ese archivo. OJO: Necesita ghostView para que PIL pueda # leer EPS. # DEPRECATED. El code39.py que solía usar ya no es el code39.py fusilado de ReportLab que uso ahora. import code39 codbar = code39.Code39() value = value.upper() f = open(value+'.eps', 'wb') codbar.generate(value, f, 'eps') f.close() return Image.open(value+'.eps'), value else: # Create a missing font file decodeFontFile(courB08_pil ,"courB08.pil") decodeFontFile(courB08_pbm ,"courB08.pbm") # Get the bar code list bits = self.makeCode(value) # Get thee bar code with the checksum added code = "" for digit in self.EAN13: code += "%d"%digit # Create a new image position = 8 im = Image.new("1",(len(bits)+position,height)) # Load font font = ImageFont.load("courB08.pil") # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0,0),(im.size[0],im.size[1])),fill=256) # Draw first part of number draw.text((0, height-9), code[0], font=font, fill=0) # Draw first part of number draw.text((position+7, height-9), code[1:7], font=font, fill=0) # Draw second part of number draw.text((len(bits)/2+6+position, height-9), code[7:], font=font, fill=0) # Draw the bar codes for bit in range(len(bits)): # Draw normal bar if bits[bit] == '1': draw.rectangle(((bit+position,0),(bit+position,height-10)),fill=0) # Draw long bar elif bits[bit] == 'L': draw.rectangle(((bit+position,0),(bit+position,height-3)),fill=0) return im, code
def make_helvetica_centered_text(imageName, text, size = 300, color = (0,0,0)): """ Draws the text on an image. If you have not downloaded the font, this function will probably crash. """ # Try loading the font my_font = ImageFont.load('C:/Python27/pilfonts/helvR24.pil') make_centered_text(imageName, text, size, my_font, color)
def getImage(self, value, filename, width=0, height=50, extension="PNG", text=False): """ Get an image with PIL library value code barre value filename file to save as height height in pixel of the bar code extension image file type text enable/disable text render (default: False) """ import Image, ImageFont, ImageDraw from string import upper # Get the bar code list bits = self.makeCode(value) # Create a new image position = 2 im = Image.new("1", (len(bits) + position, height)) # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0, 0), (im.size[0], im.size[1])), fill=256) if text: # Create a missing font file decodeFontFile(courB08_pil, "courB08.pil") decodeFontFile(courB08_pbm, "courB08.pbm") # Load font font = ImageFont.load("courB08.pil") # Draw text draw.text((0, height - 9), value, font=font, fill=0) # Create room at bottom for text when code is generated. height = height - 10 # Draw the bar codes for bit in range(len(bits)): if bits[bit] == '1': draw.rectangle(((bit + position, 0), (bit + position, height)), fill=0) # Resize if needed if width != 0: im = im.resize((width, height)) # Save the result image im.save(filename, upper(extension))
def Init(self, size = (10,10), colormode = "RGB", text = '', font = '/fonts/helvB12.pil' , textcolor = (0,0,0), color = (255,255,255)): # size self.__size = size # colormode if not colormode in ["RGB", "RGBA", "1", "L", "P", "XYZ"]: raise error.Error, 'Das Farbformat fuer den Titelhintergrund ist nicht korrekt!' self.__colormode = colormode # text if not isinstance(text, types.StringType): raise error.Error, 'Die Titelzeile ist kein String!' s = ImageFont.load(font) if not (s.getsize(text)[0] < self.__size[0]): raise error.Error, 'Die Titelzeile ist zu lang!' self.__text = text # color self.__color = color # textcolor self.__textcolor = textcolor # font self.__font = ImageFont.load(font)
def __init__(self, interval=3): """ Constructor :type interval: int :param interval: Check interval, in seconds """ self.interval = interval self.channel_data = dict() self.histogram_data = list() self.showlight = False for i in chanlookup: self.channel_data[i] = dict() # Rows and chain length are both required parameters: if args.nolights is False: self.matrix = Adafruit_RGBmatrix(16, 1) # use a bitmap font if args.nolights is False: self.font = ImageFont.load("rpi-rgb-led-matrix/fonts/4x6.pil") if args.nolights is False: self.font2 = ImageFont.load("rpi-rgb-led-matrix/fonts/5x7.pil") thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution
def getImage(self, value, height = 50, extension = "PNG"): """ Get an image with PIL library value code barre value height height in pixel of the bar code extension image file extension""" import Image, ImageFont, ImageDraw from string import lower, upper # Create a missing font file decodeFontFile(courB08_pil ,"courB08.pil") decodeFontFile(courB08_pbm ,"courB08.pbm") # Get the bar code list bits = self.makeCode(value) # Get thee bar code with the checksum added code = "" for digit in self.EAN13: code += "%d"%digit # Create a new image position = 8 im = Image.new("1",(len(bits)+position,height)) # Load font font = ImageFont.load("courB08.pil") # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0,0),(im.size[0],im.size[1])),fill=256) # Draw first part of number draw.text((0, height-9), code[0], font=font, fill=0) # Draw first part of number draw.text((position+7, height-9), code[1:7], font=font, fill=0) # Draw second part of number draw.text((len(bits)/2+6+position, height-9), code[7:], font=font, fill=0) # Draw the bar codes for bit in range(len(bits)): # Draw normal bar if bits[bit] == '1': draw.rectangle(((bit+position,0),(bit+position,height-10)),fill=0) # Draw long bar elif bits[bit] == 'L': draw.rectangle(((bit+position,0),(bit+position,height-3)),fill=0) # Save the result image im.save(code+"."+lower(extension), upper(extension))
def draw_subway_row(matrix, route_color, route_number, direction, minutes, station, row_start): if not matrix: raise Exception('No adafruit matrix passed') if (type(route_number) != 'string'): route_number = str(route_number) if (type(minutes) != 'string'): minutes = str(minutes) font = ImageFont.load(FONT_PATH) small_font = ImageFont.load(SMALL_FONT_PATH) row_width = 64 row_height = 8 x = 0 y = 0 circle_d = 6 circle_text_y_offset = 1 circle_text_x_offset = 2 text_offset = 45 station_letters = 6 image = Image.new('RGB', (row_width, row_height)) draw = ImageDraw.Draw(image) # background draw.rectangle((x, y, row_width, row_height), fill=BLACK) # subway line draw.ellipse(((x, y), (x + circle_d, y + circle_d)), fill=route_color) draw.text((x + circle_text_x_offset, y + circle_text_y_offset), route_number, font=small_font, fill=WHITE) # information draw.text((8, y), direction, font=font, fill=WHITE) draw.text((50, y), 'min', font=font, fill=WHITE) if int(minutes) > 9: text_offset -= 5 station_letters -= 1 draw.text((14, y), station[:station_letters], font=font, fill=WHITE) draw.text((text_offset, y), minutes, font=font, fill=ORANGE) matrix.SetImage(image.im.id, x, row_start)
def RightLegend(self, x, y, font): s = ImageFont.load(font) h = self.__bottommost - self.__topmost wid = [] for i in range(0, len(x)): wid.append(s.getsize(str(x[i]) + str(y[i]))[0] + 20) maxwid = max(wid) maxhi = s.getsize(str(x[0]))[1] + 10 vnum = (h - 10) / maxhi hnum = len(x) / vnum + 1 self.__legendsize = (hnum*maxwid, h) self.__legendlocation = (self.__rightmost - self.__legendsize[0], self.__topmost) self.__rightmost = self.__rightmost - self.__legendsize[0] - self.__dist
def BottomLegend(self, x, y, font): s = ImageFont.load(font) w = self.__rightmost - self.__leftmost wid = [] for i in range(0, len(x)): wid.append(s.getsize(str(x[i]) + str(y[i]))[0] + 20) maxwid = max(wid) maxhi = s.getsize(str(x[0]))[1] + 10 hnum = (w - 10) / maxwid vnum = len(x) / hnum + 1 self.__legendsize = (w, vnum*maxhi) self.__legendlocation = (self.__leftmost, self.__bottommost - self.__legendsize[1] - self.__dist) self.__bottommost = self.__bottommost - self.__legendsize[1] - self.__dist
def load_font(path, size): """Load the PIL or TrueType font""" try: # first check if the font looks like a PILfont with open(path, 'rb') as f: if f.readline() == b"PILfont\n": font = ImageFont.load(path) # otherwise assume it's a TrueType font else: font = ImageFont.truetype(path, size) except IOError: error("Invalid font: '{}'".format(path)) return font
def __init__(self, dev, text, font=None, fontFile="data/helvetica8.pil", width=40): import ImageDraw, Image, ImageFont if font is None: font = ImageFont.load(fontFile) self.font = font self.dev = dev self.text = text self.frame = Image.new("1", (width, 8)) self.draw = ImageDraw.Draw(self.frame) self.textWidth = self.draw.textsize(text, font=font)[0]
def Init(self, x = [0], y = [0], names = [], size = (10,10), text = '', color = (255,255,255), colorlist = [], font = '/fonts/helvB10.pil', textcolor = (0,0,0), colormode='RGB'): self.__x = x self.__y = y self.__names = names self.__size = size s = ImageFont.load(font) wid = [] for i in range(0, len(self.__x)): wid.append(s.getsize(str(self.__x[i]) + str(self.__y[i]))[0] + 20) maxwid = max(wid) maxhi = s.getsize(str(x[0]))[1] + 10 self.__rows = (self.__size[1] - 10) / maxhi + 1 self.__cols = len(self.__x) / self.__rows + 1 self.__text = text self.__color = color self.__colorlist = colorlist self.__colormode = 'RGB' self.__colorlist = colorlist self.__font = ImageFont.load(font)
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)
def main(): usage = 'usage: %prog [options] (in_text|-) out_image' parser = OptionParser(usage=usage, version='%%prog %s' % __version__) parser.add_option('-f', '--font', type='str', dest='font', help='Font file for rendering text', ) parser.add_option('-s', '--size', type='int', dest='size', default=12, help='Font size (only available for TrueType of OpenType fonts) [default: %default]', ) parser.add_option('-p', '--padding', type='int', dest='padding', default=5, help='Text to border in pixels [default: %default]', ) parser.add_option('-l', '--line-height', type='float', dest='line_height', default=1.1, help='Line height in font-height [default: %default]', ) parser.add_option('-b', '--background', type='str', dest='background', default='#444', help='Background color [default: %default]', ) parser.add_option('-c', '--color', type='str', dest='color', default='#aaa', help='Text color [default: %default]', ) parser.add_option('--border', type='int', dest='border', default=5, help='Border width in pixels [default: %default]', ) parser.add_option('--border-color', type='str', dest='border_color', default='#000', help='Border color [default: %default]', ) options, args = parser.parse_args() if len(args) != 2: parser.error('Need both in_text (or -, from standard input) and out_image') # Loading font if options.font: try: if options.font.endswith('.ttf') or options.font.endswith('.otf'): font = ImageFont.truetype(options.font, options.size) else: font = ImageFont.load(options.font) except IOError, e: print e parser.error('Can not load font from %s' % options.font)
def __init__(self, message): if settings.TEXT_FONT_PATH.lower().strip().endswith('ttf'): font = ImageFont.truetype( settings.TEXT_FONT_PATH, settings.TEXT_FONT_SIZE, encoding = "unic") else: font = ImageFont.load( settings.TEXT_FONT_PATH, encoding = "unic") size = font.getsize( message) size = ( size[0]*2, int(size[1] * 1.2)) image = Image.new( 'RGBA', size , settings.TEXT_BACKGROUND_COLOR) try: PIL_VERSION = int(NON_DIGITS_RX.sub('',Image.VERSION)) except: PIL_VERSION = 116 xpos = 2 for char in message: if( char!=' '): fgimage = Image.new( 'RGB', size, settings.TEXT_FOREGROUND_COLOR) charimage = Image.new( 'RGB', font.getsize(' %s '%char), '#000000') chardraw = ImageDraw.Draw( charimage) chardraw.text( ( 0,0), '%s' % char, font=font, fill='#ffffff') if settings.TEXT_LETTER_ROTATION: if PIL_VERSION >= 116: charimage = charimage.rotate( random.randrange( *settings.TEXT_LETTER_ROTATION ), expand=0, resample=Image.BICUBIC) else: charimage = charimage.rotate( random.randrange( *settings.TEXT_LETTER_ROTATION ), resample=Image.BICUBIC) charimage = charimage.crop( charimage.getbbox()) maskimage = Image.new( 'L', size) maskimage.paste( charimage, (xpos, 4 + ( 12 - charimage.size[1]), xpos+charimage.size[0], 4 + ( 12 - charimage.size[1]) + charimage.size[1])) size = maskimage.size image = Image.composite( fgimage, image, maskimage) xpos = xpos + 2 + charimage.size[0] else: xpos = xpos + 8 image = image.crop((0,0,xpos+1,size[1])) self.out = StringIO() image.save( self.out, "PNG") self.out.seek( 0) super( text, self).__init__( content_type = 'image/png', status = 200, content = self.out.read(), )
def Draw_Pie(self): id = Image.new(self.__colorformat, self.__size, self.__backgroundcol) im = ImageDraw.Draw(id) font = ImageFont.load('/fonts/' + self.__font) fontt = ImageFont.load('/fonts/' + self.__titlefont) blc = (self.__xmargin, self.__ymargin + self.__piesize[1]) brc = (self.__xmargin + self.__piewidth, self.__ymargin + self.__piesize[1]) center = (blc[0] + self.__piewidth / 2, blc[1] - self.__piedepth / 2 - self.__pieheight) im.ellipse([blc[0], blc[1] - self.__piedepth, brc[0], brc[1]], self.__piesidecol, self.__piesidecol) im.rectangle([blc[0], blc[1] - self.__piedepth / 2, brc[0], brc[1] - self.__piedepth / 2 - self.__pieheight], self.__piesidecol, self.__piesidecol) im.line([(blc[0], blc[1] - self.__piedepth / 2), (blc[0] + self.__piewidth, blc[1] - self.__piedepth / 2)], self.__piesidecol) im.ellipse([blc[0], blc[1] - self.__piedepth - self.__pieheight, brc[0], brc[1] - self.__pieheight], self.__piesidecol, self.__piesidecol) sum = 0 for i in range(0, len(self.__y)): sum = sum + self.__y[i] s = 0.0 for i in range(0, len(self.__y)): ang = ((self.__y[i]*1.0) / sum) * 360 im.pieslice([blc[0], blc[1] - self.__piedepth - self.__pieheight, brc[0], brc[1] - self.__pieheight], s, s + ang, self.__colors[i], self.__colors[i]) s = s + ang for i in range(0, len(self.__y), 2): im.text((self.__xmargin, self.__size[1] - self.__piebottommargin + i/2*15 +10), self.__x[i] + ':', self.__colors[i], font) im.text((self.__xmargin + 300, self.__size[1] - self.__piebottommargin + i/2*15 +10), str(self.__y[i]), self.__colors[i], font) if i+1 < len(self.__y): im.text((self.__xmargin + 400, self.__size[1] - self.__piebottommargin + i/2*15 +10), self.__x[i+1] + ':', self.__colors[i+1], font) im.text((self.__xmargin + 600, self.__size[1] - self.__piebottommargin + i/2*15 +10), str(self.__y[i+1]), self.__colors[i+1], font) if self.__title != '': im.text((self.__piesize[0] + 30, 30), self.__title, self.__titlefontcol, fontt) id.save(open(self.__filename, "w"), self.__fileformat)
def main(argv): if len(argv) < 4: print("invalid arguments") print("usage: python process_font.py FONT.pil FONT_NAME FONT_SIZE") return False file_name = argv[1] font_name = argv[2] font_size = argv[3] try: font = ImageFont.load(file_name) except IOError, e: print("Failed to open font file! {0}".format(e)) return False
def generate_montage(filenames): images = [Image.open(filename) for filename in filenames] width = 0 height = 0 i = 0 sum_x = max_y = 0 width = max(image.size[1]+margin for image in images)*row_size height = sum(image.size[0]+margin for image in images) montage = Image.new(mode='RGBA', size=(width, height), color=(0,0,0,0)) try: image_font = ImageFont.truetype('font/Helvetica.ttf', 18) except: try: image_font = ImageFont.load('font/Helvetica-18.pil') except: image_font = ImageFont.load_default() draw = ImageDraw.Draw(montage) offset_x = offset_y = 0 i = 0 max_y = 0 max_x = 0 offset_x = 0 for image in images: montage.paste(image, (offset_x, offset_y)) text_coords = offset_x + image.size[0] - 45, offset_y + 120 draw.text(text_coords, '#{0}'.format(i+1), font=image_font) max_x = max(max_x, offset_x+image.size[0]) if i % row_size == row_size-1: offset_y += max_y+margin max_y = 0 offset_x = 0 else: offset_x += image.size[0]+margin max_y = max(max_y, image.size[1]) i += 1 if i % row_size: offset_y += max_y filename = strftime("Montage %Y-%m-%d at %H.%M.%S.png") montage = montage.crop((0, 0, max_x, offset_y)) montage.save(filename)
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,size[1]) image = Image.new('RGB', size , settings.CAPTCHA_BACKGROUND_COLOR) xpos = 2 for char in text: 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 hasattr(Image,'VERSION') and int(Image.VERSION.replace('.','')) >= 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 getImage(self, value, filename, width = 0, height = 50, extension = "PNG", text = False): """ Get an image with PIL library value code barre value filename file to save as height height in pixel of the bar code extension image file type text enable/disable text render (default: False) """ import Image, ImageFont, ImageDraw from string import upper # Get the bar code list bits = self.makeCode(value) # Create a new image position = 2 im = Image.new("1",(len(bits)+position,height)) # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0,0),(im.size[0],im.size[1])),fill=256) if text: # Create a missing font file decodeFontFile(courB08_pil ,"courB08.pil") decodeFontFile(courB08_pbm ,"courB08.pbm") # Load font font = ImageFont.load("courB08.pil") # Draw text draw.text((0, height-9), value, font=font, fill=0) # Create room at bottom for text when code is generated. height = height - 10 # Draw the bar codes for bit in range(len(bits)): if bits[bit] == '1': draw.rectangle(((bit+position,0),(bit+position,height)),fill=0) # Resize if needed if width != 0: im = im.resize((width, height)) # Save the result image im.save(filename, upper(extension))
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,size[1]) image = Image.new('RGB', size , settings.CAPTCHA_BACKGROUND_COLOR) xpos = 2 for char in text: 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') charimage = charimage.rotate(random.randrange( *settings.CAPTCHA_LETTER_ROTATION ), expand=0, 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(using='megavideo'out,"PNG") out.seek(0) response = HttpResponse() response['Content-Type'] = 'image/png' response.write(out.read()) return response
def drawSymbol(self, loc, angle, label = None): pointList = [] if type(label) == type("") and len(label) >= 2 and label[0] == '"': label = label[1:-1] elif label: label = self.getSymbol(label) else: label = self.getSymbol(1) colorNum = self.getColor(label) if self.symbols: self.drawObj.text(loc, label, font = ImageFont.load(self.fontFilename), fill = self.indexToColor(colorNum) ) else: self.drawObj.line([(loc[0], loc[1]), (loc[0] + self.length * math.sin(angle), loc[1] + self.length * math.cos(angle))], fill = self.indexToColor(colorNum)) self.drawObj.ellipse( (loc[0] - 2, loc[1] - 2, loc[0] + 2, loc[1] + 2), fill = (0, 0, 0))
def drawOnPIL(self): """ Funciona igual que el método "draw" y "drawOnDW" sólo que usa PIL para dibujar. Necesita los archivos de fuentes usados en EANBarCode. """ try: import Image, ImageFont, ImageDraw except ImportError: from PIL import Image, ImageFont, ImageDraw from informes.barcode.EANBarCode import decodeFontFile, courB08_pil, courB08_pbm, FDEST_PIL, FDEST_PBM # Fuente: decodeFontFile(courB08_pil, FDEST_PIL) decodeFontFile(courB08_pbm, FDEST_PBM) font = ImageFont.load(FDEST_PIL) # Imagen: im = Image.new("1", map(int, (self.width, self.height + 15))) # Lienzo: dw = ImageDraw.Draw(im) # Comienzo con lienzo en blanco: dw.rectangle(((0,0),(im.size[0],im.size[1])),fill=256) # Dibujo el número dw.text((self.width * 0.5 - len(self.value) * 1.5, im.size[1] - 12), self.value, font=font, fill=0) # Dibujo las barras: xdim = self.xdim wx = xdim * self.ratio left = self.xo b = self.bearers * xdim bb = b * 0.5 + 3 tb = self.height - (b * 1.5) for c in self.decomposed: if c == 'i': left = left + self.gap elif c == 's': left = left + xdim elif c == 'S': left = left + wx elif c == 'b': dw.rectangle(((left, bb), (left + xdim, tb)), fill = 0); left = left + xdim elif c == 'B': dw.rectangle(((left, bb), (left + wx, tb)), fill = 0); left = left + wx if self.bearers: dw.rectangle(((self.lquiet, 0.0), (self.width - (self.lquiet + self.rquiet), b)), fill = 0) dw.rectangle(((self.lquiet, self.height - b), (self.width - (self.lquiet + self.rquiet), b)), fill = 0) return im
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 legend(self, heights): template = os.path.join(self.inpath, "density.png") legend_img = os.path.join(self.target, "pop_density_legend.png") font_file = "./pilfonts/helvB14.pil" font = ImageFont.load(font_file) im = Image.open(template) draw = ImageDraw.Draw(im) text = "" X = 75 Y = 90 for h in heights: text = "%.1f\n" % (h) draw.text((X, Y), text, (0, 0, 0), font=font) Y += 47 print "saved legend to ", legend_img im.save(legend_img)
def txt2img(self, label, fontname="courB08.pil", imgformat="PNG", fgcolor=(0,0,0), bgcolor=(255,255,255),rotate_angle=0): """Render text as image.""" fontpath = pylons.config['pilfonts_dir'] font = ImageFont.load(os.path.join(fontpath,fontname)) imgOut = Image.new("RGBA", (20,49), (0,0,0,0)) # calculate space needed to render text draw = ImageDraw.Draw(imgOut) sizex, sizey = draw.textsize(label, font=font) imgOut = imgOut.resize((sizex,sizey)) # render text into image draw area draw = ImageDraw.Draw(imgOut) draw.text((0, 0), label, fill=fgcolor, font=font) if rotate_angle: imgOut = imgOut.rotate(rotate_angle) return imgOut
def legend(self, heights): template = os.path.join(self.inpath, "density.png") legend_img = os.path.join(self.target,"pop_density_legend.png") font_file = "./pilfonts/helvB14.pil" font = ImageFont.load(font_file) im = Image.open(template) draw = ImageDraw.Draw(im) text = "" X = 75 Y = 90 for h in heights: text = "%.1f\n" % (h) draw.text((X, Y), text, (0,0,0), font=font) Y += 47 print "saved legend to ", legend_img im.save(legend_img)
def drawBarCode(self, value, draw, x, y, height=30): """ Convert string value to bar code starting at (x,y) and draw onto a PIL image height specifies in pixel of the bar code """ import ImageFont # Get the bar code list bits = self.makeCode(value) # Get the bar code with the checksum added code = '' for digit in self.EAN13: code += '{n:d}'.format(n=digit) # Load font font = ImageFont.load('courB08.pil') # Draw first part of number draw.text((x, y + height - 9), code[0], font=font, fill=0) # Draw first part of number draw.text((x + 15, y + height - 9), code[1:7], font=font, fill=0) # Draw second part of number draw.text((len(bits) / 2 + 14 + x, y + height - 9), code[7:], font=font, fill=0) # Draw the bar codes for bit in range(len(bits)): # Draw normal bar if bits[bit] == '1': draw.rectangle( ((bit + x + 8, y), (bit + x + 8, y + height - 10)), fill=0) # Draw long bar elif bits[bit] == 'L': draw.rectangle( ((bit + x + 8, y), (bit + x + 8, y + height - 3)), fill=0)
def getImage(self, value, width, height = 50, extension = "PNG"): """ Get an image with PIL library value code barre value height height in pixel of the bar code extension image file extension""" import Image, ImageFont, ImageDraw from string import lower, upper # Create a missing font file decodeFontFile(courB08_pil ,"courB08.pil") decodeFontFile(courB08_pbm ,"courB08.pbm") # Get the bar code list bits = self.makeCode(value) # Create a new image position = 4 original_width = len(bits)+position im = Image.new("1",(width, height)) # Load font #font = ImageFont.truetype("symbol.ttf", 16, encoding="symb") font = ImageFont.load("courB08.pil") # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0,0),(im.size[0],im.size[1])),fill=256) # Draw text draw.text((42, height-12), value, font=font, fill=0) # Draw the bar codes for bit in range(len(bits)): if bits[bit] == '1': draw.rectangle(((bit+position,12),(bit+position,height-16)),fill=0) # Save the result image im.save(value+"."+lower(extension), upper(extension))
def getImage(self, value, height=50, extension="PNG"): """ Get an image with PIL library value code barre value height height in pixel of the bar code extension image file extension""" import Image, ImageFont, ImageDraw from string import lower, upper # Create a missing font file decodeFontFile(courB08_pil, "courB08.pil") decodeFontFile(courB08_pbm, "courB08.pbm") # Get the bar code list bits = self.makeCode(value) # Create a new image position = 8 im = Image.new("1", (len(bits) + position, height)) # Load font font = ImageFont.load("courB08.pil") # Create drawer draw = ImageDraw.Draw(im) # Erase image draw.rectangle(((0, 0), (im.size[0], im.size[1])), fill=256) # Draw text draw.text((0, height - 9), value, font=font, fill=0) # Draw the bar codes for bit in range(len(bits)): if bits[bit] == '1': draw.rectangle( ((bit + position, 0), (bit + position, height - 10)), fill=0) # Save the result image im.save(value + "." + lower(extension), upper(extension))
def drawSymbol(self, loc, angle, label=None): pointList = [] if type(label) == type("") and len(label) >= 2 and label[0] == '"': label = label[1:-1] elif label: label = self.getSymbol(label) else: label = self.getSymbol(1) colorNum = self.getColor(label) if self.symbols: self.drawObj.text(loc, label, font=ImageFont.load(self.fontFilename), fill=self.indexToColor(colorNum)) else: self.drawObj.line([(loc[0], loc[1]), (loc[0] + self.length * math.sin(angle), loc[1] + self.length * math.cos(angle))], fill=self.indexToColor(colorNum)) self.drawObj.ellipse( (loc[0] - 2, loc[1] - 2, loc[0] + 2, loc[1] + 2), fill=(0, 0, 0))
NON_DIGITS_RX = re.compile('[^\d]') 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'): try: font = ImageFont.truetype(settings.CAPTCHA_FONT_PATH, settings.CAPTCHA_FONT_SIZE) except Exception, e: print e 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
shortTimeColor = (255, 0, 0) # Short arrival time = red minsColor = (110, 110, 110) # Commans and 'minutes' labels noTimesColor = (0, 0, 255) # No predictions = blue #routeColor = (255, 255, 255) # Color for route labels (usu. numbers) #descColor = (255, 140, 0) # " for route direction/description #longTimeColor = (255, 140, 0) # Ample arrival time = green #midTimeColor = (255, 140, 0) # Medium arrival time = yellow #shortTimeColor = (255, 140, 0) # Short arrival time = red #minsColor = (255, 140, 0) # Commans and 'minutes' labels #noTimesColor = (255, 255, 255) # No predictions = blue # TrueType fonts are a bit too much for the Pi to handle -- slow updates and # it's hard to get them looking good at small sizes. A small bitmap version # of Helvetica Regular taken from X11R6 standard distribution works well: font = ImageFont.load( os.path.dirname(os.path.realpath(__file__)) + '/fonts/helvetica-8.pil') fontYoffset = -2 # Scoot up a couple lines so descenders aren't cropped # Main application ----------------------------------------------------------- # Drawing takes place in offscreen buffer to prevent flicker image = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(image) currentTime = 0.0 prevTime = 0.0 # Clear matrix on exit. Otherwise it's annoying if you need to break and # fiddle with some code while LEDs are blinding you. def clearOnExit(): matrix.Clear()
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)
height = 16 # types (incl. tiling). Other code may need tweaks. matrix = Adafruit_RGBmatrix(16, 1) # rows, chain length fps = 12 # Scrolling speed (ish) routeColor = (255, 255, 255) # Color for route labels (usu. numbers) descColor = (110, 110, 110) # " for route direction/description longTimeColor = (0, 255, 0) # Ample arrival time = green midTimeColor = (255, 255, 0) # Medium arrival time = yellow shortTimeColor = (255, 0, 0) # Short arrival time = red minsColor = (110, 110, 110) # Commans and 'minutes' labels noTimesColor = (0, 0, 255) # No predictions = blue # TrueType fonts are a bit too much for the Pi to handle -- slow updates and # it's hard to get them looking good at small sizes. A small bitmap version # of Helvetica Regular taken from X11R6 standard distribution works well: font = ImageFont.load( os.path.dirname(os.path.realpath(__file__)) + '/helvR08.pil') fontYoffset = -2 # Scoot up a couple lines so descenders aren't cropped # Main application ----------------------------------------------------------- # Drawing takes place in offscreen buffer to prevent flicker image = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(image) currentTime = 0.0 prevTime = 0.0 # Clear matrix on exit. Otherwise it's annoying if you need to break and # fiddle with some code while LEDs are blinding you. def clearOnExit(): matrix.Clear()
#!/usr/bin/python import csv import urllib import time import ImageDraw from PIL import Image import ImageFont from rgbmatrix import Adafruit_RGBmatrix matrix = Adafruit_RGBmatrix(32, 1) font = ImageFont.load("10x20.pil") url = "http://api.thingspeak.com/channels/15486/feed.csv?key=1X5610SMHNUIF9XL" def gettemp(url): response = urllib.urlopen(url) cr = csv.reader(response) rows = list(cr) row1 = rows[100] return row1[2] #print "Current temp is " + gettemp(url) +" degrees." count = 0 while (count < 100): image = Image.new("RGB", (512, 32), (0, 0, 0)) red = (255, 0, 0) draw = ImageDraw.Draw(image) drawstring = "Current temp is " + gettemp(url) + " degrees." draw.text((0, 0), drawstring, font=font, fill=red)
def __load_fonts(self): """ Load the fonts that will be used by the display """ self.font1 = ImageFont.truetype(AmpView.FONT1, 10) self.font2 = ImageFont.load(AmpView.FONT2) self.font3 = ImageFont.truetype(AmpView.FONT3, 8)
def main(): usage = 'usage: %prog [options] (in_text|-) out_image' parser = OptionParser(usage=usage, version='%%prog %s' % __version__) parser.add_option( '-f', '--font', type='str', dest='font', help='Font file for rendering text', ) parser.add_option( '-s', '--size', type='int', dest='size', default=12, help= 'Font size (only available for TrueType of OpenType fonts) [default: %default]', ) parser.add_option( '-p', '--padding', type='int', dest='padding', default=5, help='Text to border in pixels [default: %default]', ) parser.add_option( '-l', '--line-height', type='float', dest='line_height', default=1.1, help='Line height in font-height [default: %default]', ) parser.add_option( '-b', '--background', type='str', dest='background', default='#444', help='Background color [default: %default]', ) parser.add_option( '-c', '--color', type='str', dest='color', default='#aaa', help='Text color [default: %default]', ) parser.add_option( '--border', type='int', dest='border', default=5, help='Border width in pixels [default: %default]', ) parser.add_option( '--border-color', type='str', dest='border_color', default='#000', help='Border color [default: %default]', ) options, args = parser.parse_args() if len(args) != 2: parser.error( 'Need both in_text (or -, from standard input) and out_image') # Loading font if options.font: try: if options.font.endswith('.ttf') or options.font.endswith('.otf'): font = ImageFont.truetype(options.font, options.size) else: font = ImageFont.load(options.font) except IOError, e: print e parser.error('Can not load font from %s' % options.font)
### Global parameters resolveSearch = 1 # resolve hostname for search nodes ageDecay = 40 # amount of color do decay on each hop ipStart = None # ip to draw link depth from xplanetParms = None # extra parameters for xplanet map drawUNodes = 0 # should i draw user nodes too ? worldMap = 0 # should i draw a world map and plot nodes ? # Colors snColor = (100,200,200) unColorFire = (200,0,0) unColor = (200,200,200) peerLine = (255,0,0) userLine = (100,100,100) # Fonts try: ifoSmall = ImageFont.load("fonts/courR08.pil") ifoDate = ImageFont.truetype("fonts/Vera.ttf",28) ifoStats = ImageFont.truetype("fonts/Vera.ttf",20) ifoSearch = ImageFont.truetype("fonts/Vera.ttf",20) except: print "Error loading font files, make sure they are on \"fonts/\"" sys.exit() ### Global vars global searchNodes,userNodes,visited #TODO: refactor these global parms to a "env" container object. It's really annoying to "declare" them global on every function when needed. searchNodes = [] userNodes = [] visited = [] # list of visited arcs fireWalled = 0 # counts the number of firewalled nodes
RGBwhite = (255, 255, 255) RGBred = (255, 0, 0) RGBgreen = (0, 255, 0) RGBblue = (0, 0, 255) RGByellow = (255, 255, 0) RGBmagenta = (255, 0, 255) RGBcyan = (0, 255, 255) RGBColors = [ RGBwhite, RGBred, RGBgreen, RGBblue, RGByellow, RGBmagenta, RGBcyan ] #font = ImageFont.load(os.path.dirname(os.path.realpath(__file__)) + '/helvR08.pil') #font = ImageFont.load('/home/pi/LEDMatrix/rpi-rgb-led-matrix-master/helvR08.pil') font = ImageFont.load('helvR08.pil') fontYoffset = -2 font_height = 18 font_topspace = 7 # Application class Message: def __init__(self, text, color): self.text = text #The message as a string. self.color = color #The intended message color. class MessageSlot: def __init__(self, x, y, still_frames):
def make_letter_image(imgName, fontpath, letter, size=20, color=(0, 0, 0)): ''' creates an bitmap image where letter letter is centered. ''' my_font = ImageFont.load(fontpath) make_centered_text(imgName, letter, size, my_font, color)
#slabs = filter(lambda slab: len(slab) > 0, slabs) #print "Num unused slabs:", num_slabs - len(slabs) #num_slabs = len(slabs) max_height = max(len(slab) for slab in slabs) max_width = min( MAX_SLAB_WIDTH_PX, max((bb.num_bytes + (BB_ALIGN - 1)) / BYTE_RATIO for bb in BBS)) num_slab_rows = (num_slabs + MAX_SLABS_X_AXIS - 1) / MAX_SLABS_X_AXIS WIDTH_PX = max_width * MAX_SLABS_X_AXIS HEIGHT_PX = max_height * num_slab_rows import Image, ImageDraw, ImageFont font = ImageFont.load("/home/pag/Code/pilfonts/courB08.pil") img = Image.new('RGB', (WIDTH_PX, HEIGHT_PX), "black") allocators = set(bb.allocator for bb in BBS) allocators = list(allocators) allocators.sort() allocator_nums = dict(zip(allocators, range(len(allocators)))) allocators = set(allocators) # Get a color palette: http://stackoverflow.com/a/876872/247591 import colorsys N = len(allocators) print "Number of used allocators:", N HSV_tuples = [(x * 1.0 / N, (N - x) * 1.0 / N, 0.5) for x in range(N)] RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)