Esempio n. 1
0
def cli(ctx):
    """Matrix Clock"""
    ctx.log(click.style("Running Clock.", fg="cyan"))
    ctx.vlog(click.style("Clock Debug", fg="red"))

    while True:
        image = Image.new("RGB", (128, 32), (0, 0, 0))
        fnt_small = ImageFont.load(f"/home/pi/BlinkyLED/blinky/fonts/4x6.pil")
        fnt_med = ImageFont.load(f"/home/pi/BlinkyLED/blinky/fonts/9x15.pil")
        fnt_big = ImageFont.load(f"/home/pi/BlinkyLED/blinky/fonts/10x20.pil")
        color_a = (194, 112, 29)  # orange
        color_b = (29, 167, 194)  # cyan
        color_c = (194, 29, 29)  # red
        color_d = (29, 194, 45)  # green
        color_e = (142, 35, 161)  # purple

        clock()
        draw = ImageDraw.Draw(image)
        draw.rectangle((0, 0, 127, 31), fill=(0, 0, 0),
                       outline=(0, 0, 128))  # border
        draw.text((2, 1), str(ctx.date_now), font=fnt_med, fill=color_b)
        draw.text((45, 13), str(ctx.time_now), font=fnt_big, fill=color_e)
        ctx.vlog(click.style("Matrix Set", fg="red"))
        ctx.matrix.SetImage(image)
        time.sleep(1)
        clear = lambda: os.system('clear')
        clear()
Esempio n. 2
0
 def __init__(self, splash_duration=5, splash_images=None):
     # type: (int, list) -> object
     """
     OlED display module that allows you to show system information on the screen.
     Call Update() with a parameter of type [customtypes].SystemInfo
     :param splash_duration: total time to show Splash images at startup
     :param splash_images: Image names in a list. Must be mode=gray scale and exactly of size=128x128px
     """
     logger.debug("OLEDManager starting...")
     self._data = None
     self._activate_screen = False
     self.splash_logos = splash_images  # MUST BE mode=gray_scale, size=128x1218px
     self.splash_duration = splash_duration  # seconds
     self.font_std = ImageFont.load(
         OledManager.path_join("fonts/courB10.pil"))
     self.font_h1 = ImageFont.load(
         OledManager.path_join("fonts/courB18.pil"))
     self.font_xl = ImageFont.load(
         OledManager.path_join("fonts/courB24.pil"))
     self.img_host = None  # pre-rendered images
     self.img_network = None
     self.img_cpu = None
     self.img_disk = None
     self._OLED_ScanDir = OLED_Driver.SCAN_DIR_DFT  # SCAN_DIR_DFT = D2U_L2R
     self.OLED = OLED_Driver.OLED()
     self.OLED.OLED_Init(self._OLED_ScanDir)
     time.sleep(0.5)
     self._display_event = threading.Event()
     self._thread = threading.Thread(
         target=self._internal_thread_loop)  # , args=[False])
     self._thread.name = "oled_internal_thread"
     self._thread.do_run = True
     self._thread.start()
     logger.info("OLEDManager init complete")
Esempio n. 3
0
def _load_font(font, size):
    if isinstance(font, ImageFont.ImageFont):
        return font
    try:
        f = _FONT_CACHE[(font, None)]
    except KeyError:
        try:
            f = _FONT_CACHE[(font, size)]
        except KeyError:
            if font.endswith('.pil') and not os.path.exists(font):
                # PIL's internal font format is rather annoying in that it
                # requires *two* files (of which only one is specified in the
                # load() method). As a result, we can't use resource_stream
                # and have to (potentially) extract the resources to the
                # file-system (and register a manual clean-up routine).
                atexit.register(cleanup_resources)
                pil_file = resource_filename(__name__, font)
                # pylint: disable=unused-variable
                pbm_file = resource_filename(__name__, font[:-4] + '.pbm')
                f = ImageFont.load(pil_file)
                _FONT_CACHE[(font, None)] = f
            else:
                try:
                    f = ImageFont.load(font)
                    _FONT_CACHE[(font, None)] = f
                except OSError:
                    f = ImageFont.truetype(font, size)
                    _FONT_CACHE[(font, size)] = f
    return f
Esempio n. 4
0
    def render(self, game):

        image, draw = self.draw_small_scoreboard(game)
        team_font = ImageFont.load(big_font)

        # draw the inning or game start time
        w, h = team_font.getsize(game.ordinal)
        draw.text((5, 19), game.ordinal, font=team_font, fill=(255, 255, 255))

        if game.status == GameStatus.ACTIVE:
            if game.is_inning_top:
                draw.point(self.draw_pixels(small_up_arrow_pixels, 6 + w, 20))
            else:
                draw.point(self.draw_pixels(small_down_arrow_pixels, 6 + w,
                                            23))

            # draw balls/outs/strikes

            balls_strikes = "{}-{}".format(game.balls, game.strikes)
            small = ImageFont.load(small_font)
            w, h = small.getsize(balls_strikes)
            draw.text((61 - w, 18),
                      balls_strikes,
                      font=small,
                      fill=(255, 255, 255))

            for i in range(0, 3):
                x = 61 - w + i * 4
                y = 19 + h + 3
                if game.outs > i:
                    draw.point(self.draw_pixels(square_3x3_filled, x, y))
                else:
                    draw.point(self.draw_pixels(square_3x3_open, x, y))

        return image
def get_font_for_character(character):
    font_dir = os.path.join(app.root_path, 'static', 'css', 'fonts')
    if character.lower() == 'sans':
        return ImageFont.load(os.path.join(font_dir, 'a skele-ton.pil'))
    elif character.lower() == 'papyrus':
        return ImageFont.load(os.path.join(font_dir, 'NYEH HEH HEH!.pil'))
    else:
        return ImageFont.truetype(os.path.join(font_dir, 'DTM-Mono.otf'), 13)
Esempio n. 6
0
def get_font_for_character(character):
    font_dir = os.path.join(app.root_path, 'static', 'css', 'fonts')
    if character.lower() == 'sans':
        return ImageFont.load(os.path.join(font_dir, 'a skele-ton.pil'))
    elif character.lower() == 'papyrus':
        return ImageFont.load(os.path.join(font_dir, 'NYEH HEH HEH!.pil'))
    else:
        return ImageFont.truetype(os.path.join(font_dir, 'DTM-Mono.otf'), 13)
Esempio n. 7
0
    def __init__(self, resources_dir):
	self.img = Image.new('L', (176, 264))
    	self.d = ImageDraw.Draw(self.img)
    	self.d.rectangle(xy=(0, 0, 176, 264), fill=255)
    	self.d.rectangle(xy=(0, 0, 176, 17), fill=200)
	self.scheduleCount = 0

        self.font08 = ImageFont.load(resources_dir + "/helvO08.pil")
        self.fontB08 = ImageFont.load(resources_dir + "/helvB08.pil")
        self.font10 = ImageFont.load(resources_dir + "/timR10.pil")
        self.fontB10 = ImageFont.load(resources_dir + "/timB10.pil")
Esempio n. 8
0
 def __init__(self, brickConfiguration, usedSensors=None):
     self.cfg = brickConfiguration
     dir = os.path.dirname(__file__)
     self.font_s = ImageFont.load(os.path.join(dir, 'ter-u12n_unicode.pil'))
     self.font_x = ImageFont.load(os.path.join(dir, 'ter-u18n_unicode.pil'))
     self.lcd = ev3dev.Screen()
     self.led = ev3dev.Leds
     self.keys = ev3dev.Button()
     self.sound = ev3dev.Sound
     (self.font_w, self.font_h) = self.lcd.draw.textsize('X',
                                                         font=self.font_s)
     self.timers = {}
     self.sys_bus = None
     self.bt_server = None
     self.bt_connections = []
Esempio n. 9
0
    def __init__(self,
                 x=0,
                 y=0,
                 color=(255, 255, 255),
                 size=12,
                 width=64,
                 height=64,
                 font=None):
        super(DateWidget, self).__init__(x, y, color, size, width, height)
        if font:
            self.font = ImageFont.load("fonts/" + font)
        else:
            self.font = ImageFont.load("fonts/" + self.size2font(size))

        self.lastday = -1
Esempio n. 10
0
    def draw_page(self):
        # get an image
        dir_path = os.path.dirname(os.path.abspath(__file__))
        img_path = dir_path + '/assets/info_page.png'
        base = Image.open(img_path).convert('RGBA')
        fff = Image.new(base.mode, base.size, (255, ) * 4)
        img = Image.composite(base, fff, base)

        # make a blank image for the text, initialized as transparent
        txt = Image.new('RGBA', base.size, (255, 255, 255, 0))

        # get a font
        font_path = dir_path + '/assets/HaxM-12.pil'
        font14 = ImageFont.load(font_path)
        font_path = dir_path + '/assets/HaxM-13.pil'
        font20 = ImageFont.load(font_path)
        font_path = dir_path + '/assets/HaxN-17.pil'
        font30 = ImageFont.load(font_path)
        # get a drawing context
        d = ImageDraw.Draw(txt)

        # uptime
        d.text((35, 2), PageInfo.uptime(), font=font14, fill="black")

        # connected users
        d.text((20, 33),
               PageInfo.get_connected_users(),
               font=font30,
               fill="black")

        # network stats
        try:
            stat = PageInfo.network('wlan0')
            d.text((58, 35),
                   "Tx: %s" % PageInfo.bytes2human(stat.bytes_sent),
                   font=font20,
                   fill="black")
            d.text((58, 47),
                   "Rx: %s" % PageInfo.bytes2human(stat.bytes_recv),
                   font=font20,
                   fill="black")
        except KeyError:
            # no wifi enabled/available
            pass

        out = Image.alpha_composite(img, txt)
        self.device.display(out.convert(self.device.mode))
        self.device.show()
Esempio n. 11
0
 def getFont(self, fontsize):
     """ Try to load font from known location in OMERO """
     try:
         font = ImageFont.truetype(self.fontPath, fontsize)
     except:
         font = ImageFont.load('%s/pilfonts/B%0.2d.pil' % (self.GATEWAYPATH, 24))
     return font
Esempio n. 12
0
    def get_imagefont(self, font, size = None):
        try:
            # font parameter as ttf filename
            return ImageFont.truetype(font, size), True
        except OSError:
            pass

        try:
            # font parameter as ttf filename in font dir
            _font = font
            if not _font.endswith(".ttf"):
                _font += ".ttf"
            return ImageFont.truetype(os.path.join(self.FONT_DIR, _font), size), True
        except OSError:
            pass

        try:
            # font parameter as PIL bitmap font filename
            _font = font
            if not _font.endswith(".pil"):
                _font += ".pil"
            return ImageFont.load(os.path.join(self.FONT_DIR, _font)), False
        except OSError:
            pass

        try:
            # font parameter as font name
            return ImageFont.truetype(self.get_font(font), size), True
        except (OSError, ValueError):
            pass

        raise ValueError("No font found for query '{0}'.".format(font))
Esempio n. 13
0
def generate_image_from_message(msg='Hello!',
                                font="7x7.ttf",
                                font_size=8,
                                font_is_bitmap=False):
    W = 52  # width of git commit history
    H = 7  # height of git commit history

    # L because we only need 8-bit black and white
    img = Image.new('L', (W, H), 'white')

    # use PIL to 'draw' the font text onto a canvas and query it for pixel values without saving it
    draw = ImageDraw.Draw(img)
    if font_is_bitmap:
        font = ImageFont.load('fonts/' + font)
    else:
        font = ImageFont.truetype('fonts/' + font, font_size)
    w, h = font.getsize(msg)
    center_pos = (0, (H - h))
    draw.text(center_pos, msg, (0), font=font)
    image_matrix = [[[] for i in range(W)] for i in range(H)]
    # translate pixel color values (range 0-255) into gitfiti values (0-4)
    for y in range(H):
        for x in range(W):
            image_matrix[y][x] = math.ceil((255 - img.getpixel(
                (x, y))) / math.ceil(255.0 / 4.0))

    # sanity check warning just in case the input message seems longer than max-width
    if w >= W:
        print(
            "\nWARNING!\n Your message with this font seems to exceed GitHub commit history max width.\n Your results might be less than satisfactory.\nWARNING!"
        )

    return image_matrix
Esempio n. 14
0
    def render(msg):
        msg, spoilers = clean_spoilers(msg)

        # Render text
        char_size = (16, 32)  # (width, height)
        width = char_size[0] * len(msg)
        image = Image.new("RGBA", (width, char_size[1]), (0, 0, 0, 0))
        draw = ImageDraw.Draw(image)
        font = ImageFont.load("./ter-x32b.pil")  # Terminus 32px
        draw.text((0, 0), msg, font=font)

        # Pixelate spoilers
        for start, end in spoilers:
            box = (start * char_size[0], 0, end * char_size[0], char_size[1])
            ic = image.crop(box)

            # Pixelate by downscaling then upscaling
            small_size = (ic.size[0] // 8, ic.size[1] // 8)
            small = ic.resize(small_size, resample=Image.BOX)
            ic = small.resize(ic.size, Image.NEAREST)

            image.paste(ic, box)

        # Save image to buffer as png
        buf = io.BytesIO()
        image.save(buf, format="PNG")
        return io.BytesIO(buf.getvalue())
Esempio n. 15
0
def test_draw(request, tmp_path):
    tempname = save_font(request, tmp_path)
    font = ImageFont.load(tempname)
    im = Image.new("L", (130, 30), "white")
    draw = ImageDraw.Draw(im)
    draw.text((0, 0), message, "black", font=font)
    assert_image_similar_tofile(im, "Tests/images/test_draw_pbm_target.png", 0)
Esempio n. 16
0
    def draw_small_scoreboard(self, game, image=None):
        log.info("Drawing small scoreboard, game " + game.id)
        if image is None:
            image = Image.new("RGB", (self.width, self.height))
        draw = ImageDraw.Draw(image)  # let's draw on this image
        team_font = ImageFont.load(small_font)

        # add teams
        draw.rectangle(((0, 0), (64, 6)), fill=game.away.primary_color)
        draw.rectangle(((0, 0), (2, 6)), fill=game.away.secondary_color)
        draw.text((5, 1), game.away.display_name,
                  font=team_font, fill=game.away.secondary_color)
        away_score_message = str(game.away_score)
        w, _ = team_font.getsize(away_score_message)
        draw.text((61 - w, 1), str(game.away_score),
                  font=team_font, fill=game.away.secondary_color)

        draw.rectangle(((0, 7), (64, 13)), fill=game.home.primary_color)
        draw.rectangle(((0, 7), (2, 13)), fill=game.home.secondary_color)
        draw.text((5, 8), game.home.display_name,
                  font=team_font, fill=game.home.secondary_color)
        home_score_message = str(game.home_score)
        w, _ = team_font.getsize(home_score_message)
        draw.text((61 - w, 8), str(game.home_score),
                  font=team_font, fill=game.home.secondary_color)

        return (image, draw)
Esempio n. 17
0
    def render(self, game):

        image, draw = self.draw_big_scoreboard(game)
        team_font = ImageFont.load(big_font)
        # add period
        draw.text((5, 22), game.ordinal, font=team_font, fill=(255, 255, 255))

        # add FINAl
        if game.status == GameStatus.END:
            draw.text((37, 22), "FINAL", font=team_font, fill=(255, 255, 0))
        else:
            # add powerplay
            message = ""
            powerplay = False
            if game.away_powerplay:
                powerplay = True
                message = game.away.abbreviation
            if game.home_powerplay:
                powerplay = True
                message = game.home.abbreviation
            if 1 < game.away_skaters < 5 and 1 < game.home_skaters < 5:
                powerplay = True
                message = "{}-{}".format(game.away_skaters, game.home_skaters)
            if powerplay:
                w, h = team_font.getsize(message)
                rightPoint = 63 - w - 3
                draw.rectangle(((rightPoint, 21), (rightPoint + w + 2, 30)),
                               fill=(255, 255, 0))
                draw.text((rightPoint + 2, 22),
                          message,
                          font=team_font,
                          fill=(0, 0, 0))

        return image
def create_image_from_text(text):
    """Creates a 24-pixel wide image featuring the given text"""
    try:
        text = text.encode('ascii', 'ignore')
        #no TTF, they get antialiased!
        font = ImageFont.load("fonts/helvB12.pil")  #22, clear
        #font = ImageFont.load("courB14.pil") #20 pixels, bold ish
        #font = ImageFont.load("charR14.pil") #23, seify
        #font = ImageFont.load("timR14.pil") #22, ick
        #font = ImageFont.load("term14.pil") #22, ick

        width, height = font.getsize(text)
        border_width = 2

        img = Image.new("1", (border_width * 2 + width, 24), 1)
        #24 pixels high, length is arbitrary
        width, height = img.size
        draw = ImageDraw.Draw(img)
        draw.line(((0, 1), (width, 1)), fill=0)
        draw.line(((0, height - 2), (width, height - 2)), fill=0)
        draw.text((border_width, border_width), text, 0, font=font)
        draw = ImageDraw.Draw(img)
        img = img.rotate(90)
        img.save("a_test.png")
        return img
    except Exception as exception:
        print(exception)
def create_image_from_text(text):
    """Creates a 24-pixel wide image featuring the given text"""
    try:
        text = text.encode('ascii', 'ignore')
        #no TTF, they get antialiased!
        font = ImageFont.load("fonts/helvB12.pil") #22, clear
        #font = ImageFont.load("courB14.pil") #20 pixels, bold ish
        #font = ImageFont.load("charR14.pil") #23, seify
        #font = ImageFont.load("timR14.pil") #22, ick
        #font = ImageFont.load("term14.pil") #22, ick

        width, height = font.getsize(text)
        border_width = 2

        img = Image.new("1", (border_width*2 + width, 24), 1)
        #24 pixels high, length is arbitrary
        width, height = img.size
        draw = ImageDraw.Draw(img)
        draw.line(((0, 1), (width, 1)), fill=0)
        draw.line(((0, height - 2), (width, height - 2)), fill=0)
        draw.text((border_width, border_width), text, 0, font=font)
        draw = ImageDraw.Draw(img)
        img = img.rotate(90)
        img.save("a_test.png")
        return img
    except Exception as exception:
        print(exception)
Esempio n. 20
0
 def draw_legend(self, image):
     "draws a legend on the image"
     #
     # Create a legend on another bitmap
     # set legend width, height
     #
     w = self.legendbox[2] - self.legendbox[0]
     h = self.legendbox[3] - self.legendbox[1]
     im_legend = Image.new("RGB", (w, h), (255, 255, 255))
     im_font = ImageFont.load(font_path)
     im_draw = ImageDraw.ImageDraw(im_legend)
     im_draw.setfont(im_font)
     #
     # Put a scale down the left hand side
     #
     x1 = 0
     for y in range(5, h, 20):
         value = self.datarange * float(h - y) / float(h) + self.datamin
         text = "%5.3f" % value
         wt, ht = im_draw.textsize(text)
         im_draw.text((x1 - wt, y - ht / 2), text, fill=(0, 0, 0))
         x1 = max(wt, x1)
     #
     # Paint the legend
     #
     for y in range(h):
         value = self.datarange * float(h - y) / float(h) + self.datamin
         im_draw.line([(x1 + 5, y), (w, y)], fill=self._heatcolor(value))
     #
     # Transfer legend to a canvas
     #
     image.paste(im_legend, self.legendbox)
Esempio n. 21
0
def main(args):
    fnt = ImageFont.load(args.font)
    size = fnt.getsize('A')

    im = Image.new('RGB', size)
    draw = ImageDraw.Draw(im)

    if args.last - args.first < 1:
        raise ValueError('Invalid --first or --last')

    chars = []
    for idx in range(args.last - args.first + 1):
        draw.rectangle(((0, 0), size), fill=0)
        draw.text((0, 0), chr(idx + args.first), font=fnt)
        chars.append(gen_char(idx, idx + args.first, im.convert('1')))

    env = jinja2.Environment(loader=jinja2.FileSystemLoader(
        os.path.dirname(os.path.abspath(__file__))),
                             finalize=lambda x: '' if x is None else x)
    print(
        env.get_template(args.template).render({
            'font': {
                'name': args.name,
                'size': size,
                'charset': args.charset,
                'first': args.first,
                'last': args.last,
            },
            'chars': chars,
            'created': time.ctime()
        }))
Esempio n. 22
0
def _test_high_characters(request, tmp_path, message):
    tempname = save_font(request, tmp_path)
    font = ImageFont.load(tempname)
    im = Image.new("L", (750, 30), "white")
    draw = ImageDraw.Draw(im)
    draw.text((0, 0), message, "black", font=font)
    assert_image_similar_tofile(im, "Tests/images/high_ascii_chars.png", 0)
Esempio n. 23
0
def annotate(idx, blend_filename, timestamp):
	basename		= os.path.basename(blend_filename)
	dirname			= os.path.dirname(blend_filename)
	
	filename		= "%06d.jpg" % idx
	
	annotated_filename 	= os.path.join(outputDir, filename)
	
	try:
		if force or not os.path.isfile(annotated_filename):	

			logger.debug( "annotating: %s from %s", annotated_filename, blend_filename)
		
			im				= Image.open(blend_filename).convert('RGB')
			draw			= ImageDraw.Draw(im)
			text			= timestamp
			font_file   	= os.path.join(defaultDir, "pilfonts", "timR10.pil")
			font 			= ImageFont.load(font_file)
			fontsize		= 10
	
			xoff			= int(width/2 - len(timestamp))
			yoff			= int(height - 50)
	
			#print "drawing text", xoff, yoff, timestamp
			draw.text((xoff, yoff),timestamp, font=font, fill=(0,0,0,255))
	
			im.save(annotated_filename)
			add_legend(annotated_filename)
	
			logger.debug( "annotated: %s", annotated_filename)

	except Exception as e:
		print e
Esempio n. 24
0
    def xtest_draw(self):

        tempname = self.save_font()
        font = ImageFont.load(tempname)
        image = Image.new("L", font.getsize(message), "white")
        draw = ImageDraw.Draw(image)
        draw.text((0, 0), message, font=font)
Esempio n. 25
0
    def addNumbers(self):
        im = Image.open(self.outputFileName)
        draw = ImageDraw.Draw(im)
        text = ""
        rng = self.max - self.min
        step = rng / 255.0
        X = 50
        Y = 245
        # font_file   	= "./pilfonts/helvB08.pil"
        font_file = "./pilfonts/timR10.pil"
        font = ImageFont.load(font_file)
        fontsize = 10
        # font			= 'arial'
        # font = ImageFont.truetype("media/text/fonts/" + font + ".ttf", fontsize, encoding="unic")

        print "rng %f step %f count %d" % (rng, step, self.count)

        # total height 	= 255
        # num labels 	= self.count
        dy = 255.0 / self.count
        print "dy %f", dy
        for line in self.data:
            if line[4] != 0:
                value = line[0]
                height = value * step
                text = "%4d" % value
                # print "y: %f %s" % (Y,text)
                draw.text((X, Y), text, (0, 0, 0), font=font)
                Y -= dy

        print "add title:", self.title
        draw.text((5, 265), self.title, font=font, fill=(0, 0, 0, 255))

        im.save(self.outputFileName)
Esempio n. 26
0
def select_font(filename, height):
    """
    Return an (actual height, font) pair with given truetype font file (or PIL
    bitmap font file) and the upper bound of width.

    Arguments
    ---------
    filename (str)
        The font filename. It can be a TrueType (.ttf) or OpenType (.otf)
        fonts. It also can be a X Window bitmap font (.bdf, .pcf) or PIL bitmap
        font (.pil).
    height (int)
        the upper bound of height of the givent font
    """
    filename = gen_pil_if_necessary(filename)
    if filename.lower().endswith('.pil'):
        font = ImageFont.load(filename)
        _w, h = font_max_size(font)
    else:
        for i in xrange(height*3/2, MIN_FONT_SIZE-1, -1):
            font = ImageFont.truetype(filename, i)
            _w, h = font_max_size(font)
            if h <= height:
                break
    #print "[INF] Font:{}; size:{}".format(filename, i)
    #ascent, descent = font.getmetrics()
    #(width, baseline), (offset_x, offset_y) = font.font.getsize(text)
    return h, font
Esempio n. 27
0
def captcha_image(request, key, scale=1):
    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 * scale)
    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(content_type='image/png')
    response.write(out.read())
    response['Content-length'] = out.tell()

    return response
def captcha(pic_name, game_type = 'dota2'):
	'''
	Captcha
	'''
	pic_name = make_valid_pic(pic_name)
	pic_path = PIC_PATH + pic_name if os.path.exists(PIC_PATH) else ''
	font_path = FONT_PATH + FONT_FILE if os.path.exists(FONT_PATH) else '' 

	if font_path.lower().strip().endswith('ttf'):
		font = ImageFont.truetype(font_path, 22)
	else:
		font = ImageFont.load(font_path)
	
	if game_type:
		text = random.choice(HEROS[game_type])
	else:
		text = ''.join(random.sample(string.letters + string.digits, 4))
	size = get_size(font, text)
	size = (size[0] * 2, int(size[1] * 1.4))

	image = make_img(size)
	xpos = 2
	from_top = 4

	char_list = [char for char in text]
	for char in char_list:
		print char
		fg_image = Image.new('RGB', size, CAPTCHA_FOREGROUND_COLOR)
		char_image = Image.new('L', get_size(font, ' %s '%char), '#000000')
		char_draw = ImageDraw.Draw(char_image)
		char_draw.text((0, 0), ' %s '%char, font = font, fill = '#ffffff')
		if CAPTCHA_LETTER_ROTATION:
			char_image = char_image.rotate(random.randrange(*CAPTCHA_LETTER_ROTATION), expand=0, resample=Image.BICUBIC)
		
		char_image = char_image.crop(char_image.getbbox())
		mask_image = Image.new('L', size)

		mask_image.paste(char_image, (xpos, from_top, xpos+char_image.size[0], from_top+char_image.size[1]))
		size = mask_image.size
		
		image = Image.composite(fg_image, image, mask_image)
		xpos = xpos + 2 + char_image.size[0]

	# centering captcha on the image
	tmp_img = make_img(size)
	tmp_img.paste(image, (int((size[0] - xpos) / 2), int((size[1] - char_image.size[1]) / 2 - from_top)))

	image = tmp_img.crop((0, 0, size[0], size[1]))
	draw = ImageDraw.Draw(image)

	image.save('image', SAVE_AS)
	for func in get_noise_func_list():
		draw = func(draw, image)
	image.save('image_noise', SAVE_AS)
	
	for func in get_filter_func_list():
		image = func(image)
	
	image.save(pic_path, SAVE_AS)
	return image, text
Esempio n. 29
0
def annotate(idx, blend_filename, timestamp):
    basename = os.path.basename(blend_filename)
    dirname = os.path.dirname(blend_filename)

    filename = "%06d.jpg" % idx

    annotated_filename = os.path.join(outputDir, filename)

    try:
        if force or not os.path.isfile(annotated_filename):

            logger.debug("annotating: %s from %s", annotated_filename,
                         blend_filename)

            im = Image.open(blend_filename).convert('RGB')
            draw = ImageDraw.Draw(im)
            text = timestamp
            font_file = os.path.join(defaultDir, "pilfonts", "timR10.pil")
            font = ImageFont.load(font_file)
            fontsize = 10

            xoff = int(width / 2 - len(timestamp))
            yoff = int(height - 50)

            #print "drawing text", xoff, yoff, timestamp
            draw.text((xoff, yoff), timestamp, font=font, fill=(0, 0, 0, 255))

            im.save(annotated_filename)
            add_legend(annotated_filename)

            logger.debug("annotated: %s", annotated_filename)

    except Exception as e:
        print e
Esempio n. 30
0
    def addNumbers(self):
        im = Image.open(self.outputFileName)
        draw = ImageDraw.Draw(im)
        text = ""
        rng = self.max - self.min
        step = rng / 255.0
        X = 50
        Y = 245
        #font_file   	= "./pilfonts/helvB08.pil"
        font_file = "./pilfonts/timR10.pil"
        font = ImageFont.load(font_file)
        fontsize = 10
        #font			= 'arial'
        #font = ImageFont.truetype("media/text/fonts/" + font + ".ttf", fontsize, encoding="unic")

        print "rng %f step %f count %d" % (rng, step, self.count)

        # total height 	= 255
        # num labels 	= self.count
        dy = 255.0 / self.count
        print "dy %f", dy
        for line in self.data:
            if line[4] != 0:
                value = line[0]
                height = value * step
                text = "%4d" % value
                #print "y: %f %s" % (Y,text)
                draw.text((X, Y), text, (0, 0, 0), font=font)
                Y -= dy

        print "add title:", self.title
        draw.text((5, 265), self.title, font=font, fill=(0, 0, 0, 255))

        im.save(self.outputFileName)
Esempio n. 31
0
    def text(self,
             surf,
             text: str,
             x: int,
             y: int,
             size=10,
             font_name="sans-serif",
             font_path="",
             color=Color.Black,
             h_align=HorizontalAlignment.Left,
             v_align=VerticalAlignment.Center):
        if font_name in ("monospace", "serif", "sans-serif"):
            font = ImageFont.truetype(
                os.path.join(BASE_DIR, f"{font_name}.ttf"), size)
        else:
            font = ImageFont.load(font_path, size)

        img = Image.fromarray(surf.img)
        draw = ImageDraw.Draw(img)
        (w, h) = draw.textsize(text, font=font)

        if h_align == HorizontalAlignment.Center:
            x -= w // 2
        elif h_align == HorizontalAlignment.Right:
            x -= w

        if v_align == VerticalAlignment.Center:
            y -= h // 2
        elif v_align == VerticalAlignment.Bottom:
            y -= h

        draw.text((x, y), text, font=font, fill=color.bgr)
        surf.img = np.array(img)
Esempio n. 32
0
def captcha_image(request, key, scale=1):
    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 * scale)
    else:
        font = ImageFont.load(settings.CAPTCHA_FONT_PATH)

    size = getsize(font, text)
    size = (size[0] * 2, int(size[1] * 1.4))
    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', getsize(font, ' %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, from_top, xpos + charimage.size[0], from_top + 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(content_type='image/png')
    response.write(out.read())
    response['Content-length'] = out.tell()

    return response
Esempio n. 33
0
def captcha_image(text, scale=1):
    CAPTCHA_FONT_PATH = os.path.normpath(
        os.path.join(os.path.join(STATICFILES_DIRS[0], 'fonts'),
                     'sketch_2.ttf'))

    if CAPTCHA_FONT_PATH.lower().strip().endswith('ttf'):
        font = ImageFont.truetype(CAPTCHA_FONT_PATH, CAPTCHA_FONT_SIZE * scale)
    else:
        font = ImageFont.load(CAPTCHA_FONT_PATH)

    size = font.getsize(text)
    size = (size[0] * 2, 50)
    image = Image.new('RGBA', size)

    try:
        PIL_VERSION = int(NON_DIGITS_RX.sub('', Image.VERSION))
    except:
        PIL_VERSION = 116
    xpos = 2

    charlist = []
    for char in text:
        charlist.append(char)
    for char in charlist:
        fgimage = Image.new('RGB', size, captcha_dark_color())
        fsize = (50, 50)
        charimage = Image.new('L', fsize, '#000000')
        chardraw = ImageDraw.Draw(charimage)
        chardraw.text((0, 0), ' %s ' % char, font=font, fill='#ffffff')

        if PIL_VERSION >= 116:
            charimage = charimage.rotate(random.randrange(
                CAPTCHA_LETTER_ROTATION_LEFT, CAPTCHA_LETTER_ROTATION_RIGHT),
                                         expand=0,
                                         resample=Image.BICUBIC)
        else:
            charimage = charimage.rotate(random.randrange(
                CAPTCHA_LETTER_ROTATION_LEFT, CAPTCHA_LETTER_ROTATION_RIGHT),
                                         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]))

    out = StringIO()
    image.save(out, "PNG")
    out.seek(0)

    response = HttpResponse(content_type='image/png')
    response.write(out.read())
    response['Content-length'] = out.tell()

    return response
Esempio n. 34
0
 def transformImage(self, img):
     dims = self.getDims()
     ret = Image.new("RGB", dims, "white")
     draw = ImageDraw.Draw(ret)
     font = "courR" + self.args["font"] + ".pil"
     path= Location.getInstance().toAbsolutePath(os.path.join("fonts", font))
     font = ImageFont.load(path)
     (w,h) = draw.textsize(self.args["charset"][-1], font)
     if self.args["mode"] == "L":
         # Convert to grayscale
         values = img.convert("L")
     else:
         # Saturate the color
         values = ImageEnhance.Color(img).enhance(4.0)
     values = values.filter(ImageFilter.MedianFilter(5))
     for y in range(0, dims[1], h):
         for x in range(0, dims[0], w):
             v = values.getpixel((x,y))
             if self.args["mode"] == "L":
                 pct =  v/255.0
                 fill = (0, 0, 0)
             else:
                 pct = sum(v)/765.0
                 fill = v
             vi = int(round(pct * (len(self.args["charset"])-1)))
             draw.text((x,y), self.args["charset"][vi], font=font, fill=fill)
     return ret
Esempio n. 35
0
def select_font(filename, height):
    """
    Return an (actual height, font) pair with given truetype font file (or PIL
    bitmap font file) and the upper bound of width.

    Arguments
    ---------
    filename (str)
        The font filename. It can be a TrueType (.ttf) or OpenType (.otf)
        fonts. It also can be a X Window bitmap font (.bdf, .pcf) or PIL bitmap
        font (.pil).
    height (int)
        the upper bound of height of the givent font
    """
    filename = gen_pil_if_necessary(filename)
    if filename.lower().endswith('.pil'):
        font = ImageFont.load(filename)
        _w, h = font_max_size(font)
    else:
        for i in xrange(height * 3 / 2, MIN_FONT_SIZE - 1, -1):
            font = ImageFont.truetype(filename, i)
            _w, h = font_max_size(font)
            if h <= height:
                break
    #print "[INF] Font:{}; size:{}".format(filename, i)
    #ascent, descent = font.getmetrics()
    #(width, baseline), (offset_x, offset_y) = font.font.getsize(text)
    return h, font
Esempio n. 36
0
    def xtest_draw(self):

        tempname = self.save_font()
        font = ImageFont.load(tempname)
        image = Image.new("L", font.getsize(message), "white")
        draw = ImageDraw.Draw(image)
        draw.text((0, 0), message, font=font)
Esempio n. 37
0
def main(args):
    fnt = ImageFont.load(args.font)
    size = fnt.getsize('A')
    
    im = Image.new('RGB', size)
    draw = ImageDraw.Draw(im)
    
    if args.last - args.first < 1:
        raise ValueError('Invalid --first or --last')
    
    chars = []
    for idx in range(args.last - args.first + 1):
        draw.rectangle(((0, 0), size), fill = 0)
        draw.text((0, 0), chr(idx + args.first), font=fnt)
        chars.append(gen_char(idx, idx + args.first, im.convert('1')))
        
    env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__))), finalize=lambda x: '' if x is None else x)
    print(env.get_template(args.template).render({
        'font': {
            'name': args.name,
            'size': size,
            'charset': args.charset,
            'first': args.first,
            'last': args.last,
        },
        'chars': chars,
        'created': time.ctime()
    }))
Esempio n. 38
0
 def __init__(self, font_path, background='#000000', foreground='#ffffff'):
     self.font = ImageFont.load(font_path)
     self.background = ImageColor.getrgb(background)
     self.foreground = ImageColor.getrgb(foreground)
     self.line_space = 2
     self.border = 10
     _, self.line_height = self.font.getsize('Mj')
Esempio n. 39
0
def draw_mosaic(posters):
    palette = Image.new('RGB', (1000,int(math.ceil(len(posters)/5.0)*325)))
    draw = ImageDraw.Draw(palette)
    srcdir = os.path.dirname(os.path.realpath(__file__))
    try:
        font = ImageFont.load(srcdir + '/ter28-16.pil')
    except:
        font = None
        notify('error', 'no font found, using tiny default font')
    x = 0
    y = 0
    for i,poster in enumerate(posters,1):
        if hasattr(poster, 'read'):
            poster_img = Image.open(poster.name)
        elif isinstance(poster, str):
            poster_img = Image.open(poster)
        else:
            print poster
            exit()
        poster_img = poster_img.resize((200,290), Image.ANTIALIAS)
        palette.paste(poster_img, (x,y))   
        draw.text((x+90, y+290), str(i), fill=(255,255,255), font=font)
        x = x + 200
        if x > 800:
            x = 0
            y = y + 325
    PreviewWindow(palette, (1000,650))
Esempio n. 40
0
 def drawtext(self, x, y, text, fonttype, red, green, blue, clear):
     self.fonthight = fonttype[fonttype.find('x') + 1:len(fonttype)]
     if not self.fonthight.isdigit():
         self.fonthight = self.fonthight[0:len(self.fonthight) - 1]
     self.fontwidth = fonttype[0:fonttype.find('x')]
     self.im = Image.new(
         "I", (len(text) * int(self.fontwidth), int(self.fonthight) - 1))
     self.draw = ImageDraw.Draw(self.im)
     # all .bdf files are converted to .pil for easy access
     self.font = ImageFont.load(
         "/programs/rpi-rgb-led-matrix-master/fonts/" + fonttype + ".pil")
     if isinstance(text, str):
         self.draw.text((0, -1),
                        text.decode("utf8").encode("iso-8859-1"),
                        font=self.font)
     elif isinstance(text, unicode):
         self.draw.text((0, -1), text.encode("iso-8859-1"), font=self.font)
     self.xy = [0, 0]
     self.xymax = self.im.size
     for self.xy[0] in range(0, self.xymax[0]):
         for self.xy[1] in range(0, self.xymax[1]):
             self.tmp = (self.xy[0], self.xy[1])
             if self.im.getpixel(self.tmp) > 0:
                 self.offsetCanvas.SetPixel(x + self.xy[0], y + self.xy[1],
                                            red, green, blue)
             elif clear == True:
                 self.offsetCanvas.SetPixel(x + self.xy[0], y + self.xy[1],
                                            0, 0, 0)
Esempio n. 41
0
    def get_imagefont(self, font, size=None):
        try:
            # font parameter as ttf filename
            return ImageFont.truetype(font, size), True
        except OSError:
            pass

        try:
            # font parameter as ttf filename in font dir
            _font = font
            if not _font.endswith(".ttf"):
                _font += ".ttf"
            return ImageFont.truetype(os.path.join(self.FONT_DIR, _font),
                                      size), True
        except OSError:
            pass

        try:
            # font parameter as PIL bitmap font filename
            _font = font
            if not _font.endswith(".pil"):
                _font += ".pil"
            return ImageFont.load(os.path.join(self.FONT_DIR, _font)), False
        except OSError:
            pass

        try:
            # font parameter as font name
            return ImageFont.truetype(self.get_font(font), size), True
        except (OSError, ValueError):
            pass

        raise ValueError("No font found for query '{0}'.".format(font))
Esempio n. 42
0
    def __init__(self, text, scroll_off=False, text_color=(255, 255, 255), hold_time=3, text_speed=1.5, flash_text=False):
        super(TextForeground, self).__init__()
        self.__font = ImageFont.load('/usr/share/fonts/bitmap/proggy/ProggyCleanSZ.pil')
        # self.__font = ImageFont.load_default()
        self.__hold_time_temp = hold_time
        self.__reset = True
        self.__hold_time = hold_time
        self.__text_speed = text_speed
        self.__text_color = text_color
        self.__text = text
        self.__y = 2
        # self.__x = -1 * float('inf')
        self.__scroll_off = scroll_off
        self.__text_length = self.__font.getsize(text)[0]
        self.__x = 2 * self.__text_length - 1

        self.used = False

        if scroll_off:
            self.__stop = -1 * self.__text_length
        else:
            self.__stop = (self.screen_width - self.__text_length) / 2

        if flash_text:
            self.__x = self.__stop
Esempio n. 43
0
    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"""
        from PIL import Image, ImageFont, ImageDraw

        # Create a missing font file
        decodeFontFile(courB08_pil, "Dados/courB08.pil")
        decodeFontFile(courB08_pbm, "Dados/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("Dados/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("Dados/" + code + "." + extension.lower(), extension.upper())
Esempio n. 44
0
 def test_draw(self):
     tempname = self.save_font()
     font = ImageFont.load(tempname)
     im = Image.new("L", (130, 30), "white")
     draw = ImageDraw.Draw(im)
     draw.text((0, 0), message, "black", font=font)
     with Image.open("Tests/images/test_draw_pbm_target.png") as target:
         self.assert_image_similar(im, target, 0)
Esempio n. 45
0
 def _test_high_characters(self, message):
     tempname = self.save_font()
     font = ImageFont.load(tempname)
     im = Image.new("L", (750, 30), "white")
     draw = ImageDraw.Draw(im)
     draw.text((0, 0), message, "black", font=font)
     with Image.open("Tests/images/high_ascii_chars.png") as target:
         self.assert_image_similar(im, target, 0)
Esempio n. 46
0
 def test_draw(self):
     tempname = self.save_font()
     font = ImageFont.load(tempname)
     im = Image.new("L", (130,30), "white")
     draw = ImageDraw.Draw(im)
     draw.text((0, 0), message, 'black', font=font)
     with Image.open('Tests/images/test_draw_pbm_target.png') as target:
         self.assert_image_similar(im, target, 0)
Esempio n. 47
0
 def _test_high_characters(self, message):
     tempname = self.save_font()
     font = ImageFont.load(tempname)
     im = Image.new("L", (750,30) , "white")
     draw = ImageDraw.Draw(im)
     draw.text((0, 0), message, "black", font=font)
     with Image.open('Tests/images/high_ascii_chars.png') as target:
         self.assert_image_similar(im, target, 0)
Esempio n. 48
0
def load(name):
    """
    Loads the font specified by name and returns it as an instance of
    `PIL.ImageFont <http://pillow.readthedocs.io/en/latest/reference/ImageFont.html>`_
    class.
    """
    pil_file = pkg_resources.resource_filename('ev3dev.fonts', '{}.pil'.format(name))
    pbm_file = pkg_resources.resource_filename('ev3dev.fonts', '{}.pbm'.format(name))
    return ImageFont.load(pil_file)
Esempio n. 49
0
	def drawText(self, draw, height):
		# Load font
		font = ImageFont.load("courB08.pil")

		# Draw first part of number
		draw.text((self.position + 7, height - 9), self.codeStr[0:4], font=font, fill=0)

		# Draw second part of number
		draw.text((len(self.code)/2 + 6 + self.position, height-9), self.codeStr[4:], font=font, fill=0)
Esempio n. 50
0
def _test_high_characters(message):

    font = ImageFont.load(tempname)
    image = Image.new("L", font.getsize(message), "white")
    draw = ImageDraw.Draw(image)
    draw.text((0, 0), message, font=font)

    compare = Image.open('Tests/images/high_ascii_chars.png')
    assert_image_equal(image, compare)
Esempio n. 51
0
def make_image(text):
    font_path = current_app.config['CAPTCHA_FONT_PATH']
    font_size = current_app.config['CAPTCHA_FONT_SIZE']
    punctuation = current_app.config['CAPTCHA_PUNCTUATION']
    foreground_color = current_app.config['CAPTCHA_FOREGROUND_COLOR']
    letter_rotation =  current_app.config['CAPTCHA_LETTER_ROTATION']

    if font_path.lower().strip().endswith('ttf'):
        font = ImageFont.truetype(font_path, font_size)
    else:
        font = ImageFont.load(font_path)

    size = getsize(font, text)
    size = (size[0] * 2, int(size[1] * 1.4))
    image = Image.new('RGB', size,
                      current_app.config['CAPTCHA_BACKGROUND_COLOR'])

    try:
        PIL_VERSION = int(NON_DIGITS_RX.sub('', current_app.config['VERSION']))
    except:
        PIL_VERSION = 116
    xpos = 2

    charlist = []
    for char in text:
        if char in punctuation and len(charlist) >= 1:
            charlist[-1] += char
        else:
            charlist.append(char)

    for char in charlist:
        fgimage = Image.new('RGB', size, foreground_color)
        charimage = Image.new('L', getsize(font, ' %s ' % char), '#000000')
        chardraw = ImageDraw.Draw(charimage)
        chardraw.text((0, 0), ' %s ' % char, font=font, fill='#ffffff')
        if letter_rotation:
            if PIL_VERSION >= 116:
                charimage = charimage.rotate(random.randrange(*letter_rotation), expand=0, resample=Image.BICUBIC)
            else:
                charimage = charimage.rotate(random.randrange(*letter_rotation), resample=Image.BICUBIC)
        charimage = charimage.crop(charimage.getbbox())
        maskimage = Image.new('L', size)

        maskimage.paste(charimage, (xpos, from_top, xpos + charimage.size[0], from_top + 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 noise_functions():
        draw = f(draw, image)
    for f in filter_functions():
        image = f(image)

    return image
Esempio n. 52
0
def captcha_image(text, scale=1):
    CAPTCHA_FONT_PATH = os.path.normpath(
        os.path.join(os.path.join(os.path.join(BASE_DIR, 'static'), 'fonts'), capcha_font()))

    if CAPTCHA_FONT_PATH.lower().strip().endswith('ttf'):
        font = ImageFont.truetype(CAPTCHA_FONT_PATH, CAPTCHA_FONT_SIZE * scale)
    else:
        font = ImageFont.load(CAPTCHA_FONT_PATH)

    size = font.getsize(text)
    size = (size[0] * 2, 40)
    image = Image.new('RGBA', size)

    try:
        PIL_VERSION = int(NON_DIGITS_RX.sub('', Image.VERSION))
    except:
        PIL_VERSION = 116
    xpos = 2

    charlist = []
    for char in text:
        if char in CAPTCHA_PUNCTUATION and len(charlist) >= 1:
            charlist[-1] += char
        else:
            charlist.append(char)
    for char in charlist:
        fgimage = Image.new('RGB', size, capcha_dark_color())
        fsize = (50, 50)
        charimage = Image.new('L', fsize, '#000000')
        chardraw = ImageDraw.Draw(charimage)
        chardraw.text((0, 0), ' %s ' % char, font=font, fill='#ffffff')

        if PIL_VERSION >= 116:
            charimage = charimage.rotate(random.randrange(CAPTCHA_LETTER_ROTATION_LEFT, CAPTCHA_LETTER_ROTATION_RIGHT), expand=0,
                                         resample=Image.BICUBIC)
        else:
            charimage = charimage.rotate(random.randrange(CAPTCHA_LETTER_ROTATION_LEFT, CAPTCHA_LETTER_ROTATION_RIGHT),
                                             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]))

    out = StringIO()
    image.save(out, "PNG")
    out.seek(0)

    response = HttpResponse(content_type='image/png')
    response.write(out.read())
    response['Content-length'] = out.tell()

    return response
Esempio n. 53
0
def add_text_to_image(fname, txt, opFilename):
    """ convert an image by adding text """
    ft = ImageFont.load("T://user//dev//src//python//_AS_LIB//timR24.pil")
    wh = ft.getsize(txt)
    print("Adding text ", txt, " to ", fname, " pixels wide to file " , opFilename)
    im = Image.open(fname)
    draw = ImageDraw.Draw(im)
    draw.text((0, 0), txt, fill=(0, 0, 0), font=ft)
    del draw  
    im.save(opFilename)
Esempio n. 54
0
 def getExampleImage(self, imgs):
     img = self.transformInner(imgs)
     # Now put a label on it.
     draw = ImageDraw.Draw(img)
     font = ImageFont.load(os.path.join("fonts", "courB12.pil"))
     text = str(self)
     (w,h) = draw.textsize(text, font)
     draw.rectangle((0,0,w+10,h+10), (255,255,255))
     draw.text((5, 5), text, font=font, fill=(0,0,0))
     return img
Esempio n. 55
0
 def set_player(self):
   self.matrix.Clear()
   player_name = request.json.get('player')
   if player_name:
     image_path = join(os.path.dirname(os.path.abspath(__file__)), '4x6.pil')
     font = ImageFont.load(image_path)
     image = Image.new("1", (32, 32))
     draw  = ImageDraw.Draw(image)
     draw.text((0,13), player_name, font=font, fill='red')
     self.matrix.SetImage(image.im.id, 0, 0)
Esempio n. 56
0
 def test_textsize(self):
     tempname = self.save_font()
     font = ImageFont.load(tempname)
     for i in range(255):
         (dx,dy) = font.getsize(chr(i))
         self.assertEqual(dy, 20)
         self.assertIn(dx, (0,10))
     for l in range(len(message)):
         msg = message[:l+1]
         self.assertEqual(font.getsize(msg), (len(msg)*10,20))
Esempio n. 57
0
def captcha_image(text, scale=1):

	if settings.CAPTCHA_FONT_PATH.lower().strip().endswith('ttf'):
		font = ImageFont.truetype(settings.CAPTCHA_FONT_PATH, settings.CAPTCHA_FONT_SIZE * scale)
	else:
		font = ImageFont.load(settings.CAPTCHA_FONT_PATH)
	size = getsize(font, text)
	size = (size[0] * 2, int(size[1] * 1.4))
	if settings.CAPTCHA_BACKGROUND_COLOR == "transparent":
		image = Image.new('RGBA', size)
	else:
		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', getsize(font, ' %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, from_top, xpos + charimage.size[0], from_top + 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")
	return out.getvalue()
Esempio n. 58
0
   def getImage(self, value):
      """ Get an image with PIL library 
      value code barre value
      height height in pixel of the bar code
      extension image file extension"""
      from PIL import Image, ImageFont, ImageDraw
      from string import lower, upper
      height = 50
	  
      # 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
      return im
Esempio n. 59
0
    def __init__(self, text, font=None, text_color=None, **kwargs):
        # fill in base defaults
        defaults = dict(opacity=0.5)
        defaults.update(kwargs)
        self._fill_options(**defaults)

        # fill in specific settings
        self.text = text

        if isinstance(font, basestring):
            # `font` is a path to a font
            fontpath = font
            fontsize = 16

        elif isinstance(font, tuple):
            # `font` is a (path, size) tuple
            fontpath = font[0]
            fontsize = font[1]

        elif font is not None:
            raise TypeError("Expected 'font' to be a path to a font file "
                    "or a tuple containing (path, size).")

        try:
            if fontpath.endswith(".pil"):
                # bitmap font (size doesn't matter)
                self.font = ImageFont.load(fontpath)
            else:
                # truetype font (size matters)
                self.font = ImageFont.truetype(fontpath, fontsize)
        except:
            warnings.warn("The specified font '%s' could not be loaded" %
                    (font,), RuntimeWarning)
            font = None

        if not font:
            self.font = ImageFont.load_default()

        if text_color is None:
            # fallback to default
            self.text_color = (255,255,255)
        elif isinstance(text_color, basestring):
            # string in a form ImageColor module can process
            self.text_color = ImageColor.getrgb(text_color)
        elif isinstance(text_color, tuple):
            # tuple with (R,G,B)
            # if it has (R,G,B,A), the alpha component seems to be ignored by PIL
            # when rendering text
            self.text_color = text_color
        else:
            raise TypeError("Expected `text_color` to be tuple or string.")

        self.font_size = self.font.getsize(text)
Esempio n. 60
0
def addTextToImage(fname, txt, opFilename):
    ft = ImageFont.load("T://user//dev//src//python//aspytk//timR24.pil")  # Font - google name and download
    wh = ft.getsize(txt)
    print("Adding text '", txt, "' to", fname)
    im = Image.open(fname)
    draw = ImageDraw.Draw(im)
    # draw text in center 
    #draw.text((im.size[0]/2 - wh[0]/2, im.size[1]/2 + 20), txt, fill=(255, 255, 0), font=ft)
    # draw text on top left
#    draw.text((0, 0), txt, fill=(255, 255, 0), font=ft)
    draw.text((0, 0), txt, fill=(0, 0, 0), font=ft)
    del draw  
    im.save(opFilename)