Beispiel #1
0
def finalend():
    back_size = (538, 747)
    back_im = Image.new('RGBA', back_size, (255, 255, 255))
    im = getImage(
        "http://7xltx1.com2.z0.glb.qiniucdn.com/1570081-3090c6fbaa0725aa.jpg?imageMogr2/crop/!200x200a200a50/rotate/-6/")
    im2 = getImage(
        "http://7xltx1.com2.z0.glb.qiniucdn.com/1570081-3090c6fbaa0725aa.jpg?imageMogr2/crop/!200x200a200a50/rotate/7/")
    # im.show()

    img = Image.open("./card.png")

    back_im.paste(im, (32, 200))
    print img.split()
    back_im.paste(im2, (270, 160))

    font = (260, 340)

    back_im.paste(img, (0, 0), img.split()[3])
    # back_im.save("img.png")
    draw = ImageDraw.Draw(back_im)
    myfont = ImageFont.truetype('./heiti.ttf', size=30)
    fillcolor = "#ffffff"
    # width, height = img.size
    draw.text(font, '80%', font=myfont, fill=fillcolor)
    y = 0
    new_font_size = (108, 450 + y)

    myfont = ImageFont.truetype('./heiti.ttf', size=17)
    # '/Library/Fonts/Tahoma.ttf', size=30)
    fillcolor = "#333333"
    draw.text(new_font_size, u'妈妈我爱你\n你好啊', font=myfont, fill=fillcolor)
    back_im.save("img.png")
Beispiel #2
0
def draw_text(img, text, position=(10, 10), font='FreeSans.ttf', font_size=14, color=(0, 0, 0)):
    """Draws text over the image. Requires PIL.

    Args:
        img: The image to use.
        text: The text string to overlay.
        position: The text (x, y) position. (Default value = (10, 10))
        font: The ttf or open type font to use. (Default value = 'FreeSans.ttf')
        font_size: The text font size. (Default value = 12)
        color: The (r, g, b) values for text color. (Default value = (0, 0, 0))

    Returns: Image overlayed with text.
    """
    _check_pil()

    font_files = _find_font_file(font)
    if len(font_files) == 0:
        logger.warn("Failed to lookup font '{}', falling back to default".format(font))
        font = ImageFont.load_default()
    else:
        font = ImageFont.truetype(font_files[0], font_size)

    # Don't mutate original image
    img = Image.fromarray(img)
    draw = ImageDraw.Draw(img)
    draw.text(position, text, fill=color, font=font)
    return np.asarray(img)
Beispiel #3
0
 def __init__(self,artists,title_text):
     self.artist_list=artists
     self.title_text = title_text
     self.text_font = ImageFont.truetype(self.TT_FONT, self.TITLE_FONT_SIZE)
     self.graph_font = ImageFont.truetype(self.TT_FONT, self.GRAPH_FONT_SIZE)
     self.img = Image.new("RGBA",(self.IMAGE_WIDTH, self.IMAGE_HEIGHT),self.BG_GRAY_COLOR)
     self.create_image()
def renderTable(j1, j2, path, wedges):
	jTot = j1 + j2
	
	#Calculate the necessary image size
	divotPosition = (2*DefaultCellWidth + 6, 2*DefaultCellHeight + 2)
	imgWidth = sum([wedge.getWidthFromDivot() for wedge in wedges]) + divotPosition[0] + 1
	imgHeight = sum([wedge.getHeightFromDivot() for wedge in wedges]) + divotPosition[1] + 1
	
	#P = palette, (width, height), white background
	#See http://effbot.org/zone/creating-palette-images.htm
	img = Image.new('P',(imgWidth,imgHeight), 255)
	draw = ImageDraw.Draw(img)
	jFont = ImageFont.truetype("DejaVu.ttf", 15)
	cFont = ImageFont.truetype("DejaVu.ttf", 10)
	
	#Render the big J stuff
	j1 = getCondonShortleyForm(sqrt(j1)) #Safe to pass in sqrts because j1, j1 shouldn't be negative, although we need TODO double check this
	j2 = getCondonShortleyForm(sqrt(j2))
	j1Str = "%i/%i" % (j1[1], j1[2]) if j1[2] != 1 else "%i" % j1[1]
	j2Str = "%i/%i" % (j2[1], j2[2]) if j2[2] != 1 else "%i" % j2[1]
	draw.text((0,0), "%s X %s" % (j1Str, j2Str), font=jFont)
	
	#Positions specified as (x, y), y runs downward
	for wedge in wedges:
		divotPosition = wedge.render(draw, cFont, divotPosition)
	
	#Save file
	try:
		img.save(path)
	except(KeyError):
		print("Couldn't save due to invalid file path.")
def get_placeholder_image(width, height, name=None, fg_color=get_color('black'),
        bg_color=get_color('grey'), text=None, font=u'Verdana.ttf',
        fontsize=42, encoding=u'unic', mode='RGBA', fmt=u'PNG'):
    """Little spin-off from https://github.com/Visgean/python-placeholder
    that not saves an image and instead returns it."""
    size = (width, height)
    text = text if text else '{0}x{1}'.format(width, height)

    try:
        font = ImageFont.truetype(font, size=fontsize, encoding=encoding)
    except IOError:
        font = ImageFont.load_default()

    result_img = Image.new(mode, size, bg_color)

    text_size = font.getsize(text)
    text_img = Image.new("RGBA", size, bg_color)

    #position for the text:
    left = size[0] / 2 - text_size[0] / 2
    top = size[1] / 2 - text_size[1] / 2

    drawing = ImageDraw.Draw(text_img)
    drawing.text((left, top),
                 text,
                 font=font,
                 fill=fg_color)

    txt_img = ImageOps.fit(text_img, size, method=Image.BICUBIC, centering=(0.5, 0.5))

    result_img.paste(txt_img)
    file_obj = io.BytesIO()
    txt_img.save(file_obj, fmt)

    return file_obj.getvalue()
Beispiel #6
0
def draw_text(txt, image, k=0, x=0, y=30):
	'''takes a image and places txt on it'''
	print 'adding text:', txt.encode('utf-8')
	font_path = "resources/msjhbd.ttc"
	draw = ImageDraw.Draw(image)

	#autofit
	fontsize = 1  # starting font size
	# portion of image width you want text width to be
	img_fraction = 0.50
	font = ImageFont.truetype(font_path, fontsize)
	while font.getsize(txt)[0] < img_fraction*image.size[0]*0.7:
	    # iterate until the text size is just larger than the criteria
	    fontsize += 1
	    font = ImageFont.truetype(font_path, fontsize)

	txt = full_width(txt)
	#draw.text((0, 30), txt, fill=random_color(k) , font=font)
	# #############
	# # thin border
	# draw.text((x-1, y), txt, font=font, fill=random_color(k+200))
	# draw.text((x+1, y), txt, font=font, fill=random_color(k+200))
	# draw.text((x, y-1), txt, font=font, fill=random_color(k+200))
	# draw.text((x, y+1), txt, font=font, fill=random_color(k+200))

	# thicker border
	draw.text((x-2, y-2), txt, font=font, fill=random_color(k+90))
	draw.text((x+2, y-2), txt, font=font, fill=random_color(k+60))
	draw.text((x-2, y+2), txt, font=font, fill=random_color(k+37))
	draw.text((x+2, y+2), txt, font=font, fill=random_color(k+80))
	#################


	return image
 def getFont(self, size):
     try:
         font_path = os.path.join(self.font_path, "Fontin-Bold.otf")
         font = ImageFont.truetype(font_path, size*300/72)
         return font
     except IOError:
         return ImageFont.load_default()
Beispiel #8
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 __init__(self, width, height, args):
    # init
    self._nextframe = 0

    # screen data
    self.width = width
    self.height = height

    # Config
    self.eventtitle = args.get('event', 'Something!')
    self.strdatetime = args.get('datetime', 'Mon Dec 24 00:00:00 EST 2012')

    # Colors
    self.color = self.HTMLColorToPILColor(args.get('color', '#000000'))
    self.textcolor = self.HTMLColorToPILColor(args.get('textcolor', '#FFFFFF'))

    # Standard fonts
    self.fontfile = args.get('fontfile', 'font/DejaVuSans.ttf')
    self.fontsize = args.get('fontsize', 48)
    self.timefontsize = args.get('timefontsize', 80)
    self.timelabelfontsize = args.get('timelabelfontsize', 48)

    # Title font
    self.titlefontfile = args.get('titlefontfile', 'font/DejaVuSans.ttf')
    self.titlefontsize = args.get('titlefontsize', 100)

    # Process options
    self.datetime = dateutil.parser.parse(self.strdatetime)
    self.font = ImageFont.truetype(self.fontfile, self.fontsize)
    self.timefont = ImageFont.truetype(self.fontfile, self.timefontsize)
    self.timelabelfont = ImageFont.truetype(self.fontfile, self.timelabelfontsize)
    self.titlefont = ImageFont.truetype(self.titlefontfile, self.titlefontsize)
    def save_image(self):
        try:
            font = ImageFont.truetype(self.font, size=self.fontsize, encoding=self.encoding)
        except IOError:
            font = ImageFont.load_default()

        result_img = Image.new(self.mode, self.size, self.bg_color)

        text_size = font.getsize(self.text)
        text_img = Image.new("RGBA", self.size, self.bg_color)

        #position for the text:
        left = self.size[0] / 2 - text_size[0] / 2
        top = self.size[1] / 2 - text_size[1] / 2

        drawing = ImageDraw.Draw(text_img)
        drawing.text((left, top),
                     self.text,
                     font=font,
                     fill=self.fg_color)

        txt_img = ImageOps.fit(text_img, self.size, method=Image.BICUBIC, centering=(0.5, 0.5))

        result_img.paste(txt_img)
        txt_img.save(self.path, self.fmt)
Beispiel #11
0
	def __init__(self, parent, chrt, options, mainfr, id = -1, size = wx.DefaultSize):
		commonwnd.CommonWnd.__init__(self, parent, chrt, options, id, size)

		self.mainfr = mainfr

		self.FONT_SIZE = int(21*self.options.tablesize) #Change fontsize to change the size of the table!
		self.SPACE = self.FONT_SIZE/2
		self.LINE_HEIGHT = (self.SPACE+self.FONT_SIZE+self.SPACE)
		self.LINE_NUM = 5
		self.COLUMN_NUM = 1
		self.CELL_WIDTH = 10*self.FONT_SIZE
		self.TABLE_HEIGHT = (self.LINE_NUM)*(self.LINE_HEIGHT)
		self.TABLE_WIDTH = (self.CELL_WIDTH+self.COLUMN_NUM*self.CELL_WIDTH)

		self.TABLE2_OFFS = self.LINE_HEIGHT
		self.LINE_NUM2 = 1
		self.COLUMN_NUM2 = 2
		self.CELL_WIDTH2 = 10*self.FONT_SIZE
		self.TABLE_HEIGHT2 = (self.LINE_NUM2+1)*(self.LINE_HEIGHT)
		self.TABLE_WIDTH2 = (self.CELL_WIDTH+self.COLUMN_NUM2*self.CELL_WIDTH)

		self.WIDTH = (commonwnd.CommonWnd.BORDER+self.TABLE_WIDTH2+commonwnd.CommonWnd.BORDER)
		self.HEIGHT = (commonwnd.CommonWnd.BORDER+self.TABLE_HEIGHT+self.TABLE2_OFFS+self.TABLE_HEIGHT2+commonwnd.CommonWnd.BORDER)

		self.SetVirtualSize((self.WIDTH, self.HEIGHT))

		self.fntMorinus = ImageFont.truetype(common.common.symbols, self.FONT_SIZE)
		self.fntText = ImageFont.truetype(common.common.abc, self.FONT_SIZE)
		self.signs = common.common.Signs1
		if not self.options.signs:
			self.signs = common.common.Signs2
		self.deg_symbol = u'\u00b0'

		self.drawBkg()
Beispiel #12
0
def draw_point_label(imd, pnt, sz, letter, number, color):
    big_font = ImageFont.truetype(FONT_PATH, sz)
    small_font = ImageFont.truetype(FONT_PATH, (2 * sz) // 3)
    letter_size = big_font.getsize(letter)
    imd.text(pnt, letter, font=big_font, fill=color)
    imd.text((pnt[0] + letter_size[0], pnt[1] + sz / 2.0), number, 
             font=small_font, fill=color)
def image_placeholder(param):
    fontfile = '/usr/share/fonts/X11/TTF/arialbd.ttf'
    minsize = 5
    maxsize = 500

    try:
        param['width'] = int(param['width'])
    except:
        param['width'] = 640

    try:
        param['height'] = int(param['height'])
    except:
        param['height'] = 480

    try:
        ImageColor.getrgb(param['front'])
    except:
        param['front'] = '#666'

    try:
        ImageColor.getrgb(param['back'])
    except:
        param['back'] = '#999'

    if not param.get('text'):
        param['text'] = '%(width)s x %(height)s'

    try:
        param['text'] = param['text'] % param
    except:
        param['text'] = 'placeholder'

    img = Image.new('RGB', (param['width'], param['height']))
    draw = ImageDraw.Draw(img)
    draw.rectangle(((0, 0), (param['width'], param['height'])), fill=param['back'])

    size = (maxsize + minsize) / 2
    while size != minsize and size != maxsize:
        font = ImageFont.truetype(fontfile, size)
        textsize = draw.textsize(param['text'], font=font)

        if (textsize[0] == param['width'] and textsize[1] <= param['height']) \
        or (textsize[0] <= param['width'] and textsize[1] == param['height']):
            break

        if textsize[0] > param['width'] or textsize[1] > param['height']:
            maxsize = size
        else:
            minsize = size

        size = (maxsize + minsize) / 2

    if size:
        font = ImageFont.truetype(fontfile, size)
        textsize = draw.textsize(param['text'], font=font)

        draw.text((param['width'] / 2 - textsize[0] / 2, param['height'] / 2 - textsize[1] / 2), param['text'], fill=param['front'], font=font)

    return img
Beispiel #14
0
    def load_text(self,text,width=None,height=None,color=(255,255,255),ttf=None):
        img = Image.new("RGBA",(1000,200), (0,0,0))
        draw = ImageDraw.Draw(img)
        if ttf==None:
            font = ImageFont.load_default()
        else:
            font = ImageFont.truetype(ttf,100)

        size = draw.textsize(text, font=font)
        w,h = size
        if width==None:
            width = int(w * (float(height)/h))
        img = Image.new("RGBA",size,(0,0,0,0))
        draw = ImageDraw.Draw(img)
        draw.text((0,0), text, color, font=font )
        
        # The below silliness is because bbox does not work well with truetype fonts.
        w,h = img.size
        x1 = int(w)
        y1 = int(h)
        x2 = 0
        y2 = 0
        for y in xrange(h):
            for x in xrange(w):
                alpha = img.getpixel((x,y))[3]
                if alpha > 0:
                    x1 = min(x1,x)
                    x2 = max(x2,x)
                    y1 = min(y1,y)
                    y2 = max(y1,y)
        x2 = min(w,x2+1)
        y2 = min(h,y2+1)
        img = img.crop((x1,y1,x2,y2))
        self.load_image(width=width, height=height, image=img)
        return self
Beispiel #15
0
def wiseWord(filename, fore_text, from_text):
    font5 = ImageFont.truetype("fonts/TH Kodchasal Bold.ttf", 18)
    font6 = ImageFont.truetype("fonts/TH Kodchasal Bold.ttf", 10)
    color = random_color()
    create_imageWithNewLine(
        filename, font5, font6, color[0], color[1], fore_text, "-" + from_text + "-", image_filter="SMOOTH_MORE"
    )
Beispiel #16
0
    def __blank_tile_default(self):
        import pkg_resources
        from PIL import Image as PilImage
        from PIL import ImageDraw, ImageFont

        im = PilImage.new('RGB', (256, 256), (234, 224, 216))

        text = 'Image not available'
        try:
            font_file = pkg_resources.resource_filename(
                'mapping.enable', 'fonts/Verdana.ttf'
            )
            font = ImageFont.truetype(font_file, 18)
        except IOError:
            font = ImageFont.load_default()
        size = font.getsize(text)
        pos = (256-size[0])//2, (256-size[1])//2

        draw = ImageDraw.Draw(im)
        draw.text(pos, text, fill=(200, 200, 200), font=font)
        del draw

        tile = StringIO()
        im.save(tile, format='png')
        return Image(StringIO(tile.getvalue()))
Beispiel #17
0
    def __init__(self, coder, **options):
        """Initializes a new BarcodeImage generator.

        Arguments:
          @ coder: barcode generator
            A callable object that takes an iterable and returns a string of ones
            and zeroes that describes the barcode.
          % barwidth: int ~~ 1
            The width of the smallest bar in pixels.
          % dpi: int ~~ 96
            Print resolution of the generated images.
          % font_file: str ~~ None
            Font file to use for the barcode text. This should be a full pathname
            to a True- or Open Type font. If omitted, the default (courier) is used.
          % font_size: int ~~ 9
            The font size to use with the given font_file. This is a size in points.
          % format: str ~~ 'png'
            The output image format.
          % height: int ~~ 30 * barwidth
            The height of the generated images.
          % print_text: bool ~~ True
            Configures whether text should be printed on the baseline of the image.
        """
        self.coder = coder
        self.options = options
        self.options.setdefault('barwidth', 1)
        self.options.setdefault('height', 30 * self.options['barwidth'])
        self.options.setdefault('dpi', 96)
        self.options.setdefault('format', 'png')
        self.options.setdefault('print_text', True)
        if 'font_file' in self.options:
            self.font = ImageFont.truetype(self.options['font_file'],
                                           self.options['font_size'])
        else:
            self.font = ImageFont.load_default()
def generate_image(msg, save_path):
    font_size = 1
    img_fraction = 0.50
    msg = msg.decode("utf8")

    font = ImageFont.truetype("fonts/OpenSans-Light.ttf", font_size)

    W, H = (400, 400)

    img = Image.new("RGBA", (W, H), (255, 255, 255))
    draw = ImageDraw.Draw(img)

    while font.getsize(msg)[0] < img_fraction * img.size[0]:
        font_size += 1
        font = ImageFont.truetype("fonts/OpenSans-Light.ttf", font_size)

    font_size -= 1
    font = ImageFont.truetype("fonts/OpenSans-Light.ttf", font_size)

    w, h = draw.textsize(msg, font)

    draw.text(((W - w) / 2, (H - h) / 2), msg, fill="black", font=font)
    draw = ImageDraw.Draw(img)

    img.save(save_path)
Beispiel #19
0
 def _get_fonts(self):
     """ return fonts """
     font_fun = ImageFont.truetype(os.path.join(self.app_folder, self.font),
                                   self.nome_tam)
     font_car = ImageFont.truetype(os.path.join(self.app_folder, self.font),
                                   self.cargo_tam)
     return font_fun, font_car
Beispiel #20
0
def _get_placeholder_instance(c, text=None):
    imsize = (160, 80)
    immode = 'RGBA'
    imfont = 'Arial.ttf'
    imfontsize = 22
    imtext = c.mimetype if text is None else text
    imtext = imtext.replace('/', ' ').split(' ')
    if len(imtext) == 1:
        imtext.append(u'')
    im = Image.new(immode, imsize, '#eeeeee')
    draw = ImageDraw.Draw(im)
    try:
        font = ImageFont.truetype(imfont, imfontsize, encoding='unic')
    except IOError:
        font = ImageFont.load_default()
        raise
    
    draw.text((5,10), imtext[0], font=font, fill='#333333')
    draw.text((5,35), imtext[1], font=font, fill='#333333')
    #corners = [(0,0), 
    #           (imsize[0], 0), 
    #           (imsize[0], imsize[1]),
    #           (0, imsize[1]),
    #           (0,0)
    #           ]
    #for i in range(0,len(corners)-1):
    #    draw.line((corners[i], corners[i+1]), width=3, fill='#000000')
    del draw
    #im.save("/tmp/text.png", "PNG")
    return im 
Beispiel #21
0
 def loadable_font(filepath, size, index, encoding,
                   *args, **kwargs):
     if filepath == path_to_fake:
         return ImageFont._FreeTypeFont(FONT_PATH, size, index,
                                        encoding, *args, **kwargs)
     return ImageFont._FreeTypeFont(filepath, size, index,
                                    encoding, *args, **kwargs)
    def generate(self):
        image = Image.new("RGB", (1024, 1024), "#bfb6aa")
        draw = ImageDraw.Draw(image)
        lines = textwrap.wrap(self.text, 40)
        fsize = 48
        font = ImageFont.truetype(self.args.fontfile, fsize)
        linew = 0
        while linew < 750:
            font = ImageFont.truetype(self.args.fontfile, fsize)
            linew = font.getsize(lines[0])[0]
            fsize = int(fsize * 1.25)

        offset = 10
        maxw = 10
        for l in lines:
            draw.text((10, offset), l, font=font, fill="#000")
            offset += int(font.getsize(l)[1] * 1.3)
            maxw = max(maxw, font.getsize(l)[0])

        self.image = Image.new(
            "RGB", (maxw + 20 + 100, offset + 20 + 100), "#bfb6aa")
        self.draw = ImageDraw.Draw(self.image)
        offset = 60
        for l in lines:
            self.draw.text((60, offset), l, font=font, fill="#000")
            offset += int(font.getsize(l)[1] * 1.3)
Beispiel #23
0
def generate_badge():
    conn = get_conn(DB)
    c = conn.cursor()
    c.execute("SELECT * FROM samples ORDER BY DATE DESC LIMIT 1")
    row = c.fetchone()
    c.close()

    date = dateparser.parse(row[0])
    co2 = str(int(row[1]))

    timestamp = date.strftime("%I:%M%p")
    datestamp = date.strftime("%m/%d") if (datetime.now() - date).days > 0 else ""

    print "Generating badge: %s - %s %s" % (co2, timestamp, datestamp)

    image = Image.open("template.png")
    draw = ImageDraw.ImageDraw(image)
    font = ImageFont.truetype("arial.ttf", 10)
    draw.setfont(font)
    dw, dh = font.getsize(datestamp)
    draw.text((30 - dw / 2, 78 - dh), datestamp)
    tw, th = font.getsize(timestamp)
    draw.text((30 - tw / 2, 77 - th - dh), timestamp)
    font = ImageFont.truetype("arial.ttf", 26)
    draw.setfont(font)
    cw, ch = font.getsize(co2)
    draw.text((30 - cw / 2, 8), co2)
    image.save("webroot/badge.png")
def draw_image(job, build_status):
  freesans = ImageFont.truetype("FreeSans.ttf")
  symbola = ImageFont.truetype("Symbola.ttf", 16)

  if build_status == "SUCCESS":
    symbol = CHECKMARK
    color = GREEN
  elif build_status == "BUILD_INPROGRESS":
    symbol = None
    color = YELLOW
  else:
    symbol = CROSS
    color = RED

  width_text = freesans.getsize(job)[0]
  width = width_text

  if symbol is not None:
    width += symbola.getsize(symbol)[0]

  image = Image.new("RGB", (width, 16), "black")
  draw = ImageDraw.Draw(image)

  draw.text((0, 0), job, color, font=freesans)

  if symbol is not None:
    draw.text((width_text, 0), symbol, color, font=symbola)

  return image
Beispiel #25
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
 def _create_win(self):
     try:
         key = winreg.OpenKey(
             winreg.HKEY_LOCAL_MACHINE,
             r'Software\Microsoft\Windows NT\CurrentVersion\Fonts')
     except EnvironmentError:
         try:
             key = winreg.OpenKey(
                 winreg.HKEY_LOCAL_MACHINE,
                 r'Software\Microsoft\Windows\CurrentVersion\Fonts')
         except EnvironmentError:
             raise FontNotFound('Can\'t open Windows font registry key')
     try:
         path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True)
         self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
         for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
             path = self._lookup_win(key, self.font_name, STYLES[style])
             if path:
                 self.fonts[style] = ImageFont.truetype(path, self.font_size)
             else:
                 if style == 'BOLDITALIC':
                     self.fonts[style] = self.fonts['BOLD']
                 else:
                     self.fonts[style] = self.fonts['NORMAL']
     finally:
         winreg.CloseKey(key)
Beispiel #27
0
  def _Textmark(self, image, text, truefont=None, opacity=50):
    """Creates an image watermarked with the given text.

    Pastes the text in the given font and size TEXTMARK_HEIGHT of the image's
    height, in the bottom right corner of the image.

    Args:
      image: The image to watermark.
      text: The text to paste in the image.
      truefont: A truefont filename for the font to be used.
      opacity: The opacity of the watermark (default: 50).
    Returns:
      A new watermarked Image with the given text.
    """
    img = image.convert('RGB')
    wm = Image.new('RGBA', img.size)
    draw = ImageDraw.ImageDraw(wm, 'RGBA')
    fontsize = int(TEXTMARK_HEIGHT * img.size[1])
    if truefont:
      font = ImageFont.truetype(truefont, fontsize)
    else:
      font = ImageFont.load_default()
    textsize = font.getsize(text)
    draw.setfont(font)
    # Draw text in bottom right corner
    draw.text(((wm.size[0] - textsize[0] - TEXTMARK_SPACE),
               (wm.size[1] - textsize[1] - TEXTMARK_SPACE)), text)
    # Make transperent by adding an alpha layer on the watermark
    # (PIL alpha layer must be of type 'L' or '1')
    mask = wm.convert('L').point(lambda x: min(x, opacity))
    wm.putalpha(mask)
    img.paste(wm, None, wm)
    return img
Beispiel #28
0
def text_watermark(img, text, out_file="test4.jpg", angle=23, opacity=0.50):
    '''
    添加一个文字水印,做成透明水印的模样,应该是png图层合并
    http://www.pythoncentral.io/watermark-images-python-2x/
    这里会产生著名的 ImportError("The _imagingft C module is not installed") 错误
    Pillow通过安装来解决 pip install Pillow
    '''
    watermark = Image.new('RGBA', img.size, (255,255,255))
    FONT = "msyh.ttf"
    size = 2

    n_font = ImageFont.truetype(FONT, size)                                       #得到字体
    n_width, n_height = n_font.getsize(text)
    text_box = min(watermark.size[0], watermark.size[1])
    while (n_width+n_height <  text_box):
        size += 2
        n_font = ImageFont.truetype(FONT, size=size)
        n_width, n_height = n_font.getsize(text)                                   #文字逐渐放大,但是要小于图片的宽高最小值

    text_width = (watermark.size[0] - n_width) / 2
    text_height = (watermark.size[1] - n_height) / 2
    #watermark = watermark.resize((text_width,text_height), Image.ANTIALIAS)
    draw = ImageDraw.Draw(watermark, 'RGBA')                                       #在水印层加画笔
    draw.text((text_width,text_height),
              text, font=n_font, fill="#21ACDA")
    watermark = watermark.rotate(angle, Image.BICUBIC)
    alpha = watermark.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    watermark.putalpha(alpha)
    Image.composite(watermark, img, watermark).save(out_file, 'JPEG')
    print u"文字水印成功"
Beispiel #29
0
  def __renderText(self, data, im):

    print('Render text')

    name    = data['name']
    fields  = data['fields']
    coords  = data['fieldsCoordinates']
    colors  = data['fieldsColors']
    sizes   = data['fieldsSizes']

    namesize = 16

    if 'name' in sizes:
      namesize = sizes['name'] or 16

    draw = ImageDraw.Draw(im)
    font = ImageFont.truetype('fonts/OpenSans-Regular.ttf', namesize)

    #name
    draw.text((coords['name']['left'], coords['name']['top'] + 16), name, self.formatColor(colors['name']), font=font)

    #fields
    for fieldName, fieldValue in fields.iteritems():

      fontsize = 16

      if fieldName in sizes:
        fontsize = sizes[fieldName] or 16

      font = ImageFont.truetype('fonts/OpenSans-Regular.ttf', fontsize)
      draw.text((coords[fieldName]['left'], coords[fieldName]['top'] + 16), fieldValue, self.formatColor(colors[fieldName]), font=font)
  def __init__(self, width, height, args):
    self._nextupd = time.time()
    self.width = width
    self.height = height
    self._framespeed = 0.5
    self._dayfont = ImageFont.truetype('font/DejaVuSans.ttf',     22)
    self._mainfont = ImageFont.truetype('font/DejaVuSans.ttf',    24)
    self._daytempfont = ImageFont.truetype('font/DejaVuSans.ttf', 36)
    self._tempfont = ImageFont.truetype('font/DejaVuSans.ttf',    72)
    self._textcolor = (0,   0,   0)
    self._maxcolor  = (255, 0,   0)
    self._mincolor  = (50,   50,   255)
    self._bomxml = args.get('xmlfile', 'IDV10753.xml')
    self._bomarea = args.get('weatherdistrict', 'VIC_PT042')
    self._bomradarcode = args.get('radarcode', '023')

    self._wicon = {}
    for i in range(1, 18):
      im = Image.open('img/icons/' + str(i) + '.png').convert('RGBA')
      im = im.resize((83, 83), Image.BICUBIC)
      self._wicon[i] = im

    bomapi = BOM()
    self._wdata = bomapi.getData(self._bomarea, self._bomxml)
    self._radarloop = bomapi.getRadarLoop(self._bomradarcode)
    self._rimg = 0