Python ImageFont.truetype() Examples

The following are 16 code examples of ImageFont.truetype(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ImageFont , or try the search function .
Example #1
Source File: main.py    From rpi-magicmirror-eink with MIT License 6 votes vote down vote up
def main():
    epd = epd7in5b.EPD()
    epd.init()

    # For simplicity, the arguments are explicit numerical coordinates
    # image_red = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 255)    # 255: clear the frame
    # draw_red = ImageDraw.Draw(image_red)
    # image_black = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 255)    # 255: clear the frame
    # draw_black = ImageDraw.Draw(image_black)
    # font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24)
    # draw_red.rectangle((0, 6, 640, 40), fill = 0)
    # draw_red.text((200, 10), 'e-Paper demo', font = font, fill = 255)
    # draw_red.rectangle((200, 80, 600, 280), fill = 0)
    # draw_red.chord((240, 120, 580, 220), 0, 360, fill = 255)
    # draw_black.rectangle((20, 80, 160, 280), fill = 0)
    # draw_red.chord((40, 80, 180, 220), 0, 360, fill = 0)
    # epd.display_frame(epd.get_frame_buffer(image_black),epd.get_frame_buffer(image_red))

    # display images
    frame_black = epd.get_frame_buffer(Image.open('black.png'))
    frame_red = epd.get_frame_buffer(Image.open('white.png'))
    epd.display_frame(frame_black, frame_red) 
Example #2
Source File: Text.py    From captchacker2 with GNU General Public License v3.0 6 votes vote down vote up
def render(self, img):
        font = ImageFont.truetype(*self.font)
    	textSize = font.getsize(self.text)
        draw = ImageDraw.Draw(img)

        # Find the text's origin given our alignment and current image size
        x = int((img.size[0] - textSize[0] - self.borderSize*2) * self.alignment[0] + 0.5)
        y = int((img.size[1] - textSize[1] - self.borderSize*2) * self.alignment[1] + 0.5)

        # Draw the border if we need one. This is slow and ugly, but there doesn't
        # seem to be a better way with PIL.
        if self.borderSize > 0:
            for bx in (-1,0,1):
                for by in (-1,0,1):
                    if bx and by:
                        draw.text((x + bx * self.borderSize,
                                   y + by * self.borderSize),
                                  self.text, font=font, fill=self.borderColor)

        # And the text itself...
        draw.text((x,y), self.text, font=font, fill=self.textColor)

### The End ### 
Example #3
Source File: Text.py    From captchacker2 with GNU General Public License v3.0 6 votes vote down vote up
def render(self, img):
        font = ImageFont.truetype(*self.font)
    	textSize = font.getsize(self.text)
        draw = ImageDraw.Draw(img)

        # Find the text's origin given our alignment and current image size
        x = int((img.size[0] - textSize[0] - self.borderSize*2) * self.alignment[0] + 0.5)
        y = int((img.size[1] - textSize[1] - self.borderSize*2) * self.alignment[1] + 0.5)

        # Draw the border if we need one. This is slow and ugly, but there doesn't
        # seem to be a better way with PIL.
        if self.borderSize > 0:
            for bx in (-1,0,1):
                for by in (-1,0,1):
                    if bx and by:
                        draw.text((x + bx * self.borderSize,
                                   y + by * self.borderSize),
                                  self.text, font=font, fill=self.borderColor)

        # And the text itself...
        draw.text((x,y), self.text, font=font, fill=self.textColor)

### The End ### 
Example #4
Source File: whoisleak.py    From Whoisleak with MIT License 6 votes vote down vote up
def banner():

	ShowText = 'For Educational Purpose Only'

	font = ImageFont.truetype('arialbd.ttf', 15) #load the font
	size = font.getsize(ShowText)  #calc the size of text in pixels
	image = Image.new('1', size, 1)  #create a b/w image
	draw = ImageDraw.Draw(image)
	draw.text((0, 0), ShowText, font=font) #render the text to the bitmap
	for rownum in range(size[1]):
		line = []
		for colnum in range(size[0]):
			if image.getpixel((colnum, rownum)): line.append(' '),
			else: line.append('#'),
		print (''.join(line))

	print ("Access the site https://databases.today to download the available leaks.\n") 
Example #5
Source File: display_letters.py    From flyover with MIT License 5 votes vote down vote up
def literally_show(self, airport_code):
    display = Matrix16x8.Matrix16x8()
    display.begin()
    display.set_brightness(4)
    font = ImageFont.truetype(os.path.join(os.path.dirname(__file__), 'thintel/Thintel.ttf'), 15)
    if len(airport_code) == 4:
      image = Image.new('1', (21, 8))
      draw = ImageDraw.Draw(image)

      blankimage = Image.new('1', (16, 8))
      blankdraw = ImageDraw.Draw(blankimage)
      blankdraw.text((0, 0), '', fill=255)

      for i in xrange(58):
        n = 5 - abs((i % 12) - 5)
        draw.text((0, 0), airport_code,  font=font, fill=255)
        display.set_image(blankimage)
        display.write_display()
        display.set_image(image.crop((n, 0, n + 16, 8)))
        display.write_display()
        sleep( 0.5 if i > 0 else 3)
    elif len(airport_code) == 3 or len(airport_code) == 0:
      image = Image.new('1', (16, 8))
      draw = ImageDraw.Draw(image)
      draw.text((0, 0), airport_code,  font=font, fill=255)
      display.set_image(image)
      display.write_display() 
Example #6
Source File: ImageDraw2.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def __init__(self, color, file, size=12):
        # FIXME: add support for bitmap fonts
        self.color = ImageColor.getrgb(color)
        self.font = ImageFont.truetype(file, size) 
Example #7
Source File: writer.py    From viivakoodi with MIT License 5 votes vote down vote up
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) 
Example #8
Source File: ImageDraw2.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def __init__(self, color, file, size=12):
        # FIXME: add support for bitmap fonts
        self.color = ImageColor.getrgb(color)
        self.font = ImageFont.truetype(file, size) 
Example #9
Source File: barcode.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def _paint_text(self, xpos, ypos):
            font = ImageFont.truetype(self.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) 
Example #10
Source File: Text.py    From captchacker2 with GNU General Public License v3.0 5 votes vote down vote up
def pick(self):
        """Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()"""
        fileName = File.RandomFileFactory.pick(self)
        size = int(random.uniform(self.minSize, self.maxSize) + 0.5)
        return (fileName, size)

# Predefined font factories 
Example #11
Source File: Text.py    From captchacker2 with GNU General Public License v3.0 5 votes vote down vote up
def pick(self):
        """Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()"""
        fileName = File.RandomFileFactory.pick(self)
        size = int(random.uniform(self.minSize, self.maxSize) + 0.5)
        return (fileName, size)

# Predefined font factories 
Example #12
Source File: Text.py    From captchacker2 with GNU General Public License v3.0 5 votes vote down vote up
def pick(self):
        """Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()"""
        fileName = File.RandomFileFactory.pick(self)
        size = int(random.uniform(self.minSize, self.maxSize) + 0.5)
        return (fileName, size)

# Predefined font factories 
Example #13
Source File: ImageDraw2.py    From keras-lambda with MIT License 5 votes vote down vote up
def __init__(self, color, file, size=12):
        # FIXME: add support for bitmap fonts
        self.color = ImageColor.getrgb(color)
        self.font = ImageFont.truetype(file, size) 
Example #14
Source File: recipe-576490.py    From code with MIT License 4 votes vote down vote up
def generate_letter(contrast_energy = .01, #michelson contrast energy
                   noise = 30.,
                   bg_luminance = 128.,
                   letter = "a",
                   letter_size = 400):
 N = 300 #size of image in pixels

 #first figure out what is the ink-area of the letter

 font = ImageFont.truetype("Data/arial.ttf", letter_size)
 #we copy the .ttf file to the local directory to avoid problems

 im_temp = Image.new("1", (1,1), 0)
 draw = ImageDraw.Draw(im_temp)
 #now we can draw on this

 sz = draw.textsize(letter, font=font)
 #this tells us the size of the letter

 im_temp = Image.new("1", sz, 0)
 #this is a temporary binary image created solely for the purpose of computing
 #the ink-area of the letter
 draw = ImageDraw.Draw(im_temp)
 #now we can draw on this
 draw.text((0,0), letter, font=font, fill=1)
 pix = im_temp.load()
 #pix is now an addressable array of pixel values
 area_in_pixels = 0.
 for row in xrange(sz[0]):
   for col in xrange(sz[1]):
     area_in_pixels += pix[row,col]

 #since contrast_energy = contrast^2 * pixel_area
 contrast = (contrast_energy/area_in_pixels)**0.5
 fg_luminance = bg_luminance*(1+contrast)/(1-contrast)
 print area_in_pixels
 print contrast
 print fg_luminance


 im = Image.new("L", (N,N), bg_luminance)
 #im is now a NxN luminance image with luminance set to bg_luminance

 draw = ImageDraw.Draw(im)
 #now we can draw on this

 draw.text(((N-sz[0])/2, (N-sz[1])/2), letter, font=font, fill=fg_luminance)
 #this centers the letter

 if noise > 0:
   pix = im.load()
   #pix is now an addressable array of pixel values
  
   rd = numpy.random.normal(scale=noise, size=(N,N))
   for row in xrange(N):
     for col in xrange(N):
       pix[row,col] += rd[row,col]

 im.show() 
Example #15
Source File: redact.py    From ParanoiDF with GNU General Public License v3.0 4 votes vote down vote up
def check_word(word, redactAreaX,
 		redactAreaY, fontName, 
		fontSize): 

    imageDimensionX = redactAreaX + 10
    imageDimensionY = redactAreaY + 5
    img = Image.new('RGB', (imageDimensionX, imageDimensionY))
    d = ImageDraw.Draw(img)
    f = ImageFont.truetype(fontName, fontSize)
    d.text((0, 0), word, fill=(255,0,0), font=f)
    img = img.convert('P') 

    xAndyCoord = []
    for x in range(img.size[1]): #Get coordinates.
	for y in range(img.size[0]):
    	    pixCol = img.getpixel((y,x))
    	    if pixCol == 16 or pixCol == 15 or \
	    pixCol == 14 or pixCol == 13 or \
	    pixCol == 12 or pixCol == 11 or \
	    pixCol == 10:
		xAndyCoord.append((y,x))

    #Convert list to string.
    str1 = ''.join(str(e) for e in xAndyCoord)

    #Strip X and Y value into seperate INT variable.
    xcoord = [int(element.split(",")[0].rstrip().lstrip()) for element in str1[1:-1].split(")(")]
    ycoord = [int(element.split(",")[1].rstrip().lstrip()) for element in str1[1:-1].split(")(")]

    #X and Y maximum length for word.
    maxValueX = max(xcoord)
    maxValueY = max(ycoord)
    minValueX = min(xcoord)
    minValueY = min(ycoord)
    xLength = maxValueX - minValueX
    yLength = maxValueY - minValueY

    #Maximum/minimum threshold for word.
    maxX = redactAreaX# + 1
    minX = redactAreaX - 3
    maxY = redactAreaY# + 1
    minY = redactAreaY - 10 #Big because a word might be all low letters such as "rear".

    #If X and Y dimension falls within threshold.
    if xLength <= maxX and xLength >= minX and yLength <= maxY and yLength >= minY:
	#Success.
	return word
    else: 
	#No fit.
	return 0 
Example #16
Source File: math_flowable.py    From rst2pdf with MIT License 4 votes vote down vote up
def genImage(self):
        """Create a PNG from the contents of this flowable.

        Required so we can put inline math in paragraphs.
        Returns the file name.
        The file is caller's responsability.

        """

        dpi = 72
        scale = 10

        try:
            import Image
            import ImageFont
            import ImageDraw
            import ImageColor
        except ImportError:
            from PIL import (
                Image,
                ImageFont,
                ImageDraw,
                ImageColor,
            )

        if not HAS_MATPLOTLIB:
            img = Image.new('RGBA', (120, 120), (255, 255, 255, 0))
        else:
            width, height, descent, glyphs, rects, used_characters = self.parser.parse(
                enclose(self.s), dpi, prop=FontProperties(size=self.fontsize)
            )
            img = Image.new(
                'RGBA', (int(width * scale), int(height * scale)), (255, 255, 255, 0)
            )
            draw = ImageDraw.Draw(img)
            for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
                font = ImageFont.truetype(fontname, int(fontsize * scale))
                tw, th = draw.textsize(chr(num), font=font)
                # No, I don't understand why that 4 is there.
                # As we used to say in the pure math
                # department, that was a numerical solution.
                col_conv = ColorConverter()
                fc = col_conv.to_rgb(self.color)
                rgb_color = (int(fc[0] * 255), int(fc[1] * 255), int(fc[2] * 255))
                draw.text(
                    (ox * scale, (height - oy - fontsize + 4) * scale),
                    chr(num),
                    font=font,
                    fill=rgb_color,
                )
            for ox, oy, w, h in rects:
                x1 = ox * scale
                x2 = x1 + w * scale
                y1 = (height - oy) * scale
                y2 = y1 + h * scale
                draw.rectangle([x1, y1, x2, y2], (0, 0, 0))

        fh, fn = tempfile.mkstemp(suffix=".png")
        os.close(fh)
        img.save(fn)
        return fn