Esempio n. 1
0
  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
Esempio n. 2
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)
Esempio n. 3
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
Esempio n. 4
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")
Esempio n. 5
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()
Esempio n. 6
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. 7
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)
Esempio n. 8
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")
Esempio n. 9
0
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()
Esempio n. 10
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)
Esempio n. 11
0
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.")
Esempio n. 12
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
 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()
Esempio n. 14
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()
Esempio n. 15
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
Esempio n. 16
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"文字水印成功"
Esempio n. 17
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"
    )
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
Esempio n. 19
0
 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)
Esempio n. 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 
    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)
Esempio n. 22
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()))
Esempio n. 23
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
Esempio n. 24
0
    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)
Esempio n. 25
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()
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
Esempio n. 27
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)
Esempio n. 28
0
  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)
Esempio n. 29
0
File: hair.py Progetto: jondale/hair
    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
Esempio n. 30
0
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)
Esempio n. 31
0
    def detect_image(self, image):
        start = timer()

        if self.model_image_size != (None, None):
            assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'
            assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'
            boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))
        else:
            new_image_size = (image.width - (image.width % 32),
                              image.height - (image.height % 32))
            boxed_image = letterbox_image(image, new_image_size)
        image_data = np.array(boxed_image, dtype='float32')

        print(image_data.shape)
        image_data /= 255.
        image_data = np.expand_dims(image_data, 0)  # Add batch dimension.

        out_boxes, out_scores, out_classes = self.sess.run(
            [self.boxes, self.scores, self.classes],
            feed_dict={
                self.yolo_model.input: image_data,
                self.input_image_shape: [image.size[1], image.size[0]],
                K.learning_phase(): 0
            })
        lbox = []
        lscore = []
        lclass = []
        for i in range(len(out_classes)):
            if out_classes[i] == 0:
                lbox.append(out_boxes[i])
                lscore.append(out_scores[i])
                lclass.append(out_classes[i])
        out_boxes = np.array(lbox)
        out_scores = np.array(lscore)
        out_classes = np.array(lclass)
        print('画面中有{}个人'.format(len(out_boxes)))

        font = ImageFont.truetype(font='font/FiraMono-Medium.otf',
                    size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
        thickness = (image.size[0] + image.size[1]) // 300

        font_cn = ImageFont.truetype(font='font/asl.otf',
                                  size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
        for i, c in reversed(list(enumerate(out_classes))):
            predicted_class = self.class_names[c]
            box = out_boxes[i]
            score = out_scores[i]

            label = '{} {:.2f}'.format(predicted_class, score)
            draw = ImageDraw.Draw(image)
            label_size = draw.textsize(label, font)

            top, left, bottom, right = box
            top = max(0, np.floor(top + 0.5).astype('int32'))
            left = max(0, np.floor(left + 0.5).astype('int32'))
            bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
            right = min(image.size[0], np.floor(right + 0.5).astype('int32'))
            print(label, (left, top), (right, bottom))

            if top - label_size[1] >= 0:
                text_origin = np.array([left, top - label_size[1]])
            else:
                text_origin = np.array([left, top + 1])

            # My kingdom for a good redistributable image drawing library.
            for i in range(thickness):
                draw.rectangle(
                    [left + i, top + i, right - i, bottom - i],
                    outline=self.colors[c])
            draw.rectangle(
                [tuple(text_origin), tuple(text_origin + label_size)],
                fill=self.colors[c])
            draw.text(text_origin, label, fill=(0, 0, 0), font=font)
            show_str = '  画面中有'+str(len(out_boxes))+'个人  '
            label_size1 = draw.textsize(show_str, font_cn)
            print(label_size1)
            draw.rectangle(
                [10, 10, 10 + label_size1[0], 10 + label_size1[1]],
                fill=(255,255,0))
            draw.text((10,10),show_str,fill=(0, 0, 0), font=font_cn)

            del draw

        end = timer()
        print(end - start)
        return image
Esempio n. 32
0
def draw_graph(today, player_data_from1_to20_dict,
               player_data_from21_to40_dict, player_data_build_from1_to20_dict,
               player_data_build_from21_to40_dict):
    """
    グラフ描画
    本プログラムの中で一番の見どころ"""

    try:
        #整地
        for mcid in player_data_from1_to20_dict:
            max_data = player_data_from1_to20_dict[mcid]["23_58"]
            break

        px = 320  #pxの最小値は320
        #最大整地量に応じた規定の大きさになるまで拡大
        while True:
            if (max_data / 50000) <= px:
                break
            else:
                px += 100
        px += 50

        hour_place = 50
        background = Image.new(mode="RGB", size=(1550, px), color=0x000000)
        background_instance = ImageDraw.Draw(background)
        font = ImageFont.truetype(r"./UDDigiKyokashoN-R.ttc", size=16)

        #横軸(時間)を書く
        for h in range(24):
            background_instance.text((hour_place, px - 30),
                                     text=f"{h}時",
                                     font=font,
                                     fill=0xffffff)
            hour_place += 50
        background_instance.text((hour_place, px - 30),
                                 text="最終",
                                 font=font,
                                 fill=0xffffff)

        #画像範囲内に目盛り線を引く
        i = 0
        while True:
            background_instance.line((60, px - 35 - i, 1250, px - 35 - i),
                                     fill=0xaaaaaa,
                                     width=1)
            background_instance.text((10, px - 35 - i - 8),
                                     text=f"{i*5}万",
                                     font=font,
                                     fill=0xffffff)
            i += 100
            if i > px:
                break

        #順位ごとに違う色付け
        color_list = [
            0x00d2f4,  #金
            0xaaaaaa,  #銀(灰)
            0x3c65bc,  #銅
            0x9999ff,  #白強めの赤
            0xff9999,  #白強めの青
            0x99ff99,  #白強めの黄緑
            0x99ffff,  #白強めの黄
            0xffff99,  #白強めの水
            0xff99ff,  #白強めの紫(ピンク)
            0x99ccff,  #白強めの橙
            0xff99cc,  #白強めの紫
            0xccff99,  #何色だよコレ、私にだけ通じる言い方をすれば白の強いねりけし色
            0x99ffcc,  #これまた表現のしようがない
            0xffcc99,  #水色みたいな色
            0xcc99ff,  #ピンク
            0x00ff00,  #黄緑
            0x0000ff,  #赤
            0x00ffff,  #黄
            0xffff00,  #水
            0xff00ff  #ショッキングピンク
        ]

        i = 0
        mcid_wide = math.floor(px / 20)
        mcid_place = math.floor(mcid_wide / 2) - 8
        mcid_break_place_list = []  #最終点とMCIDを紐づけするのに使うのでその準備
        color_index = 0
        for mcid in player_data_from1_to20_dict:
            #右側にMCIDと最終整地量を入力
            break_amount = player_data_from1_to20_dict[mcid][
                "23_58"]  #最終整地量を取得
            break_amount = "{:,}".format(break_amount)
            background_instance.text((1340, mcid_place),
                                     text=f"{mcid}: {break_amount}",
                                     fill=color_list[color_index],
                                     font=font)  #1位から順に右上から等間隔にMCIDと最終整地量を入力
            mcid_break_place_list.append(mcid_place + 8)

            #時間毎の点を入力
            point_x = 50 + 10
            xy_list = []  #線を引くときに使うのでその準備
            for hour in range(25):
                if hour == 24:
                    hour = "23_58"
                try:
                    raw_data = player_data_from1_to20_dict[mcid][
                        f"{hour}"]  #時間毎の整地量を取得
                except KeyError:
                    raw_data = 0
                point_y = math.floor(raw_data / 50000)  #座標を決定
                xy = (point_x, px - 35 - point_y)  #線を引くときに使うのでその準備
                xy_list.append(xy)  #線を引くときに使うのでその準備
                background_instance.ellipse(
                    (point_x - 3, px - 35 - point_y - 3, point_x + 3,
                     px - 35 - point_y + 3),
                    fill=color_list[color_index])  #点を打つ
                point_x += 50

            xy_list.append((1340, mcid_place + 8))

            #点と点を結ぶ線を引く
            for i in range(25):
                width = 4
                if i == 24:
                    width = 2
                x_before, y_before = xy_list[i]
                x_after, y_after = xy_list[i + 1]
                background_instance.line(
                    (x_before, y_before, x_after, y_after),
                    fill=color_list[color_index],
                    width=width)

            mcid_place += mcid_wide
            color_index += 1

        background.save(f"{today}_seichi_1-20.png")  #本日のグラフとしてpng形式で保存

        for mcid in player_data_from21_to40_dict:
            max_data = player_data_from21_to40_dict[mcid]["23_58"]
            break

        px = 320  #pxの最小値は320
        #最大整地量に応じた規定の大きさになるまで拡大
        while True:
            if (max_data / 5000) <= px:
                break
            else:
                px += 100
        px += 50

        hour_place = 50
        background = Image.new(mode="RGB", size=(1550, px), color=0x000000)
        background_instance = ImageDraw.Draw(background)
        font = ImageFont.truetype(r"./UDDigiKyokashoN-R.ttc", size=16)

        #横軸(時間)を書く
        for h in range(24):
            background_instance.text((hour_place, px - 30),
                                     text=f"{h}時",
                                     font=font,
                                     fill=0xffffff)
            hour_place += 50
        background_instance.text((hour_place, px - 30),
                                 text="最終",
                                 font=font,
                                 fill=0xffffff)

        #画像範囲内に目盛り線を引く
        i = 0
        while True:
            background_instance.line((60, px - 35 - i, 1250, px - 35 - i),
                                     fill=0xaaaaaa,
                                     width=1)
            background_instance.text((10, px - 35 - i - 8),
                                     text=f"{math.floor(i*0.5)}万",
                                     font=font,
                                     fill=0xffffff)
            i += 100
            if i > px:
                break

        #順位ごとに違う色付け
        color_list = [
            0x9999ff,  #白強めの赤
            0xff9999,  #白強めの青
            0x99ff99,  #白強めの黄緑
            0x99ffff,  #白強めの黄
            0xffff99,  #白強めの水
            0xff99ff,  #白強めの紫(ピンク)
            0x99ccff,  #白強めの橙
            0xff99cc,  #白強めの紫
            0xccff99,  #何色だよコレ、私にだけ通じる言い方をすればねりけし色
            0x99ffcc,  #これまた表現のしようがない
            0xffcc99,  #水色みたいな色
            0xcc99ff,  #ピンク
            0x00ff00,  #黄緑
            0x0000ff,  #赤
            0x00ffff,  #黄
            0xffff00,  #水
            0xff00ff,  #ショッキングピンク
            0x3299ff,  #橙
            0x99ff32,  #私にだけ通じる言い方をすればねりけし色
            0xff3299  #紫(見づらいかも)
        ]

        i = 0
        mcid_wide = math.floor(px / 20)
        mcid_place = math.floor(mcid_wide / 2) - 8
        mcid_break_place_list = []  #最終点とMCIDを紐づけするのに使うのでその準備
        color_index = 0
        for mcid in player_data_from21_to40_dict:
            #右側にMCIDと最終整地量を入力
            break_amount = player_data_from21_to40_dict[mcid][
                "23_58"]  #最終整地量を取得
            break_amount = "{:,}".format(break_amount)
            background_instance.text((1340, mcid_place),
                                     text=f"{mcid}: {break_amount}",
                                     fill=color_list[color_index],
                                     font=font)  #1位から順に右上から等間隔にMCIDと最終整地量を入力
            mcid_break_place_list.append(mcid_place + 8)

            #時間毎の点を入力
            point_x = 50 + 10
            xy_list = []  #線を引くときに使うのでその準備
            for hour in range(25):
                if hour == 24:
                    hour = "23_58"
                try:
                    raw_data = player_data_from21_to40_dict[mcid][
                        f"{hour}"]  #時間毎の整地量を取得 #時間毎の整地量を取得
                except KeyError:
                    raw_data = 0
                point_y = math.floor(raw_data / 5000)  #座標を決定
                xy = (point_x, px - 35 - point_y)  #線を引くときに使うのでその準備
                xy_list.append(xy)  #線を引くときに使うのでその準備
                background_instance.ellipse(
                    (point_x - 3, px - 35 - point_y - 3, point_x + 3,
                     px - 35 - point_y + 3),
                    fill=color_list[color_index])  #点を打つ
                point_x += 50

            xy_list.append((1340, mcid_place + 8))

            #点と点を結ぶ線を引く
            for i in range(25):
                width = 4
                if i == 24:
                    width = 2
                x_before, y_before = xy_list[i]
                x_after, y_after = xy_list[i + 1]
                background_instance.line(
                    (x_before, y_before, x_after, y_after),
                    fill=color_list[color_index],
                    width=width)

            mcid_place += mcid_wide
            color_index += 1

        background.save(f"{today}_seichi_21-40.png")  #本日のグラフとしてpng形式で保存

        #建築
        for mcid in player_data_build_from1_to20_dict:
            max_data = player_data_build_from1_to20_dict[mcid]["23_58"]
            break

        px = 320  #pxの最小値は320
        #最大整地量に応じた規定の大きさになるまで拡大
        while True:
            if (max_data / 500) <= px:
                break
            else:
                px += 100
        px += 50

        hour_place = 50
        background = Image.new(mode="RGB", size=(1550, px), color=0x000000)
        background_instance = ImageDraw.Draw(background)
        font = ImageFont.truetype(r"./UDDigiKyokashoN-R.ttc", size=16)

        #横軸(時間)を書く
        for h in range(24):
            background_instance.text((hour_place, px - 30),
                                     text=f"{h}時",
                                     font=font,
                                     fill=0xffffff)
            hour_place += 50
        background_instance.text((hour_place, px - 30),
                                 text="最終",
                                 font=font,
                                 fill=0xffffff)

        #画像範囲内に目盛り線を引く
        i = 0
        while True:
            background_instance.line((60, px - 35 - i, 1250, px - 35 - i),
                                     fill=0xaaaaaa,
                                     width=1)
            background_instance.text((10, px - 35 - i - 8),
                                     text=f"{math.floor(i*0.05)}千",
                                     font=font,
                                     fill=0xffffff)
            i += 100
            if i > px:
                break

        #順位ごとに違う色付け
        color_list = [
            0x00d2f4,  #金
            0xaaaaaa,  #銀(灰)
            0x3c65bc,  #銅
            0x9999ff,  #白強めの赤
            0xff9999,  #白強めの青
            0x99ff99,  #白強めの黄緑
            0x99ffff,  #白強めの黄
            0xffff99,  #白強めの水
            0xff99ff,  #白強めの紫(ピンク)
            0x99ccff,  #白強めの橙
            0xff99cc,  #白強めの紫
            0xccff99,  #何色だよコレ、私にだけ通じる言い方をすれば白の強いねりけし色
            0x99ffcc,  #これまた表現のしようがない
            0xffcc99,  #水色みたいな色
            0xcc99ff,  #ピンク
            0x00ff00,  #黄緑
            0x0000ff,  #赤
            0x00ffff,  #黄
            0xffff00,  #水
            0xff00ff  #ショッキングピンク
        ]

        i = 0
        mcid_wide = math.floor(px / 20)
        mcid_place = math.floor(mcid_wide / 2) - 8
        mcid_break_place_list = []  #最終点とMCIDを紐づけするのに使うのでその準備
        color_index = 0
        for mcid in player_data_build_from1_to20_dict:
            #右側にMCIDと最終整地量を入力
            break_amount = player_data_build_from1_to20_dict[mcid][
                "23_58"]  #最終整地量を取得
            break_amount = "{:,}".format(break_amount)
            background_instance.text((1340, mcid_place),
                                     text=f"{mcid}: {break_amount}",
                                     fill=color_list[color_index],
                                     font=font)  #1位から順に右上から等間隔にMCIDと最終整地量を入力
            mcid_break_place_list.append(mcid_place + 8)

            #時間毎の点を入力
            point_x = 50 + 10
            xy_list = []  #線を引くときに使うのでその準備
            for hour in range(25):
                if hour == 24:
                    hour = "23_58"
                try:
                    raw_data = player_data_build_from1_to20_dict[mcid][
                        f"{hour}"]  #時間毎の整地量を取得
                except KeyError:
                    raw_data = 0
                point_y = math.floor(raw_data / 50)  #座標を決定
                xy = (point_x, px - 35 - point_y)  #線を引くときに使うのでその準備
                xy_list.append(xy)  #線を引くときに使うのでその準備
                background_instance.ellipse(
                    (point_x - 3, px - 35 - point_y - 3, point_x + 3,
                     px - 35 - point_y + 3),
                    fill=color_list[color_index])  #点を打つ
                point_x += 50

            xy_list.append((1340, mcid_place + 8))

            #点と点を結ぶ線を引く
            for i in range(25):
                width = 4
                if i == 24:
                    width = 2
                x_before, y_before = xy_list[i]
                x_after, y_after = xy_list[i + 1]
                background_instance.line(
                    (x_before, y_before, x_after, y_after),
                    fill=color_list[color_index],
                    width=width)

            mcid_place += mcid_wide
            color_index += 1

        background.save(f"{today}_build_1-20.png")  #本日のグラフとしてpng形式で保存

        for mcid in player_data_build_from21_to40_dict:
            max_data = player_data_build_from21_to40_dict[mcid]["23_58"]
            break

        px = 320  #pxの最小値は320
        #最大整地量に応じた規定の大きさになるまで拡大
        while True:
            if (max_data / 50) <= px:
                break
            else:
                px += 100
        px += 50

        hour_place = 50
        background = Image.new(mode="RGB", size=(1550, px), color=0x000000)
        background_instance = ImageDraw.Draw(background)
        font = ImageFont.truetype(r"./UDDigiKyokashoN-R.ttc", size=16)

        #横軸(時間)を書く
        for h in range(24):
            background_instance.text((hour_place, px - 30),
                                     text=f"{h}時",
                                     font=font,
                                     fill=0xffffff)
            hour_place += 50
        background_instance.text((hour_place, px - 30),
                                 text="最終",
                                 font=font,
                                 fill=0xffffff)

        #画像範囲内に目盛り線を引く
        i = 0
        while True:
            background_instance.line((60, px - 35 - i, 1250, px - 35 - i),
                                     fill=0xaaaaaa,
                                     width=1)
            background_instance.text((10, px - 35 - i - 8),
                                     text=f"{i*5}",
                                     font=font,
                                     fill=0xffffff)
            i += 100
            if i > px:
                break

        #順位ごとに違う色付け
        color_list = [
            0x9999ff,  #白強めの赤
            0xff9999,  #白強めの青
            0x99ff99,  #白強めの黄緑
            0x99ffff,  #白強めの黄
            0xffff99,  #白強めの水
            0xff99ff,  #白強めの紫(ピンク)
            0x99ccff,  #白強めの橙
            0xff99cc,  #白強めの紫
            0xccff99,  #何色だよコレ、私にだけ通じる言い方をすればねりけし色
            0x99ffcc,  #これまた表現のしようがない
            0xffcc99,  #水色みたいな色
            0xcc99ff,  #ピンク
            0x00ff00,  #黄緑
            0x0000ff,  #赤
            0x00ffff,  #黄
            0xffff00,  #水
            0xff00ff,  #ショッキングピンク
            0x3299ff,  #橙
            0x99ff32,  #私にだけ通じる言い方をすればねりけし色
            0xff3299  #紫(見づらいかも)
        ]

        i = 0
        mcid_wide = math.floor(px / 20)
        mcid_place = math.floor(mcid_wide / 2) - 8
        mcid_break_place_list = []  #最終点とMCIDを紐づけするのに使うのでその準備
        color_index = 0
        for mcid in player_data_build_from21_to40_dict:
            #右側にMCIDと最終整地量を入力
            break_amount = player_data_build_from21_to40_dict[mcid][
                "23_58"]  #最終整地量を取得
            break_amount = "{:,}".format(break_amount)
            background_instance.text((1340, mcid_place),
                                     text=f"{mcid}: {break_amount}",
                                     fill=color_list[color_index],
                                     font=font)  #1位から順に右上から等間隔にMCIDと最終整地量を入力
            mcid_break_place_list.append(mcid_place + 8)

            #時間毎の点を入力
            point_x = 50 + 10
            xy_list = []  #線を引くときに使うのでその準備
            for hour in range(25):
                if hour == 24:
                    hour = "23_58"
                try:
                    raw_data = player_data_build_from21_to40_dict[mcid][
                        f"{hour}"]  #時間毎の整地量を取得 #時間毎の整地量を取得
                except KeyError:
                    raw_data = 0
                point_y = math.floor(raw_data / 5)  #座標を決定
                xy = (point_x, px - 35 - point_y)  #線を引くときに使うのでその準備
                xy_list.append(xy)  #線を引くときに使うのでその準備
                background_instance.ellipse(
                    (point_x - 3, px - 35 - point_y - 3, point_x + 3,
                     px - 35 - point_y + 3),
                    fill=color_list[color_index])  #点を打つ
                point_x += 50

            xy_list.append((1340, mcid_place + 8))

            #点と点を結ぶ線を引く
            for i in range(25):
                width = 4
                if i == 24:
                    width = 2
                x_before, y_before = xy_list[i]
                x_after, y_after = xy_list[i + 1]
                background_instance.line(
                    (x_before, y_before, x_after, y_after),
                    fill=color_list[color_index],
                    width=width)

            mcid_place += mcid_wide
            color_index += 1

        background.save(f"{today}_build_21-40.png")  #本日のグラフとしてpng形式で保存

    except:
        unexpected_error()
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a white background
draw.rectangle((0, 0, oled.width, oled.height), outline=255, fill=255)

# Draw a smaller inner rectangle
draw.rectangle(
    (BORDER, BORDER, oled.width - BORDER - 1, oled.height - BORDER - 1),
    outline=0,
    fill=0,
)

# Load default font.
font = ImageFont.load_default()

# Draw Some Text
text = "Hello SSD1305 OLED"
(font_width, font_height) = font.getsize(text)
draw.text(
    (oled.width // 2 - font_width // 2, oled.height // 2 - font_height // 2),
    text,
    font=font,
    fill=255,
)

# Display image
oled.image(image)
oled.show()
    def draw_bounding_box_on_image(self,
                                   image,
                                   ymin,
                                   xmin,
                                   ymax,
                                   xmax,
                                   color='red',
                                   thickness=4,
                                   display_str_list=(),
                                   use_normalized_coordinates=True):
        """Adds a bounding box to an image.
            Each string in display_str_list is displayed on a separate line above the
            bounding box in black text on a rectangle filled with the input 'color'.
            If the top of the bounding box extends to the edge of the image, the strings
            are displayed below the bounding box.
            Args:
                image: a PIL.Image object.
                ymin: ymin of bounding box.
                xmin: xmin of bounding box.
                ymax: ymax of bounding box.
                xmax: xmax of bounding box.
                color: color to draw bounding box. Default is red.
                thickness: line thickness. Default value is 4.
                display_str_list: list of strings to display in box
                                  (each to be shown on its own line).
                use_normalized_coordinates: If True (default), treat coordinates
                  ymin, xmin, ymax, xmax as relative to the image.  Otherwise treat
                  coordinates as absolute.
        """
        draw = ImageDraw.Draw(image)
        im_width, im_height = image.size
        if use_normalized_coordinates:
            (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                          ymin * im_height, ymax * im_height)
        else:
            (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
        try:
            font = ImageFont.truetype('arial.ttf', 24)
        except IOError:
            font = ImageFont.load_default()

        # If the total height of the display strings added to the top of the bounding
        # box exceeds the top of the image, stack the strings below the bounding box
        # instead of above.
        display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]

        # Each display_str has a top and bottom margin of 0.05x.
        total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)

        if top > total_display_str_height:
            text_bottom = top
        else:
            text_bottom = bottom + total_display_str_height

        for display_str in display_str_list[::-1]:
            text_width, text_height = font.getsize(display_str)
            margin = np.ceil(0.05 * text_height)

            if display_str.split(':')[0] == 'person':
                img = image.crop((left, top, right, bottom))
                img_str = cv2.cvtColor(numpy.array(img), cv2.COLOR_BGR2GRAY)

                encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
                result, imgencode = cv2.imencode('.jpg', img_str, encode_param)
                data = numpy.array(imgencode)
                self.image_to_analyse = data.tostring()
Esempio n. 35
0
async def process(msg, user, client, reply, replied=None):
    if not os.path.isdir("resources"):
        os.mkdir("resources", 0o755)
        urllib.request.urlretrieve(
            'https://github.com/erenmetesar/modules-repo/raw/master/Roboto-Regular.ttf',
            'resources/Roboto-Regular.ttf')
        urllib.request.urlretrieve(
            'https://github.com/erenmetesar/modules-repo/raw/master/Quivira.otf',
            'resources/Quivira.otf')
        urllib.request.urlretrieve(
            'https://github.com/erenmetesar/modules-repo/raw/master/Roboto-Medium.ttf',
            'resources/Roboto-Medium.ttf')
        urllib.request.urlretrieve(
            'https://github.com/erenmetesar/modules-repo/raw/master/DroidSansMono.ttf',
            'resources/DroidSansMono.ttf')
        urllib.request.urlretrieve(
            'https://github.com/erenmetesar/modules-repo/raw/master/Roboto-Italic.ttf',
            'resources/Roboto-Italic.ttf')

    # Importıng fonts and gettings the size of text
    font = ImageFont.truetype("resources/Roboto-Medium.ttf",
                              43,
                              encoding="utf-16")
    font2 = ImageFont.truetype("resources/Roboto-Regular.ttf",
                               33,
                               encoding="utf-16")
    mono = ImageFont.truetype("resources/DroidSansMono.ttf",
                              30,
                              encoding="utf-16")
    italic = ImageFont.truetype("resources/Roboto-Italic.ttf",
                                33,
                                encoding="utf-16")
    fallback = ImageFont.truetype("resources/Quivira.otf",
                                  43,
                                  encoding="utf-16")

    # Splitting text
    maxlength = 0
    width = 0
    text = []
    for line in msg.split("\n"):
        length = len(line)
        if length > 43:
            text += textwrap.wrap(line, 43)
            maxlength = 43
            if width < fallback.getsize(line[:43])[0]:
                if "MessageEntityCode" in str(reply.entities):
                    width = mono.getsize(line[:43])[0] + 30
                else:
                    width = fallback.getsize(line[:43])[0]
            next
        else:
            text.append(line + "\n")
            if width < fallback.getsize(line)[0]:
                if "MessageEntityCode" in str(reply.entities):
                    width = mono.getsize(line)[0] + 30
                else:
                    width = fallback.getsize(line)[0]
            if maxlength < length:
                maxlength = length

    title = ""
    try:
        details = await client(
            functions.channels.GetParticipantRequest(reply.chat_id, user.id))
        if isinstance(details.participant, types.ChannelParticipantCreator):
            title = details.participant.rank if details.participant.rank else "Creator"
        elif isinstance(details.participant, types.ChannelParticipantAdmin):
            title = details.participant.rank if details.participant.rank else "Admin"
    except TypeError:
        pass
    titlewidth = font2.getsize(title)[0]

    # Get user name
    lname = "" if not user.last_name else user.last_name
    tot = user.first_name + " " + lname

    namewidth = fallback.getsize(tot)[0] + 10

    if namewidth > width:
        width = namewidth
    width += titlewidth + 30 if titlewidth > width - namewidth else -(
        titlewidth - 30)
    height = len(text) * 40

    # Profile Photo BG
    pfpbg = Image.new("RGBA", (125, 600), (0, 0, 0, 0))

    # Draw Template
    top, middle, bottom = await drawer(width, height)
    # Profile Photo Check and Fetch
    yes = False
    color = random.choice(COLORS)
    async for photo in client.iter_profile_photos(user, limit=1):
        yes = True
    if yes:
        pfp = await client.download_profile_photo(user)
        paste = Image.open(pfp)
        os.remove(pfp)
        paste.thumbnail((105, 105))

        # Mask
        mask_im = Image.new("L", paste.size, 0)
        draw = ImageDraw.Draw(mask_im)
        draw.ellipse((0, 0, 105, 105), fill=255)

        # Apply Mask
        pfpbg.paste(paste, (0, 0), mask_im)
    else:
        paste, color = await no_photo(user, tot)
        pfpbg.paste(paste, (0, 0))

    # Creating a big canvas to gather all the elements
    canvassize = (middle.width + pfpbg.width,
                  top.height + middle.height + bottom.height)
    canvas = Image.new('RGBA', canvassize)
    draw = ImageDraw.Draw(canvas)

    y = 80
    if replied:
        # Creating a big canvas to gather all the elements
        replname = "" if not replied.sender.last_name else replied.sender.last_name
        reptot = replied.sender.first_name + " " + replname
        replywidth = font2.getsize(reptot)[0]
        if reply.sticker:
            sticker = await reply.download_media()
            stimg = Image.open(sticker)
            canvas = canvas.resize(
                (stimg.width + pfpbg.width, stimg.height + 160))
            top = Image.new("RGBA", (200 + stimg.width, 300),
                            (29, 29, 29, 255))
            draw = ImageDraw.Draw(top)
            await replied_user(draw, reptot,
                               replied.message.replace("\n", " "), 20)
            top = top.crop((135, 70, top.width, 300))
            canvas.paste(pfpbg, (0, 0))
            canvas.paste(top, (pfpbg.width + 10, 0))
            canvas.paste(stimg, (pfpbg.width + 10, 140))
            os.remove(sticker)
            return True, canvas
        canvas = canvas.resize((canvas.width + 60, canvas.height + 120))
        top, middle, bottom = await drawer(middle.width + 60, height + 105)
        canvas.paste(pfpbg, (0, 0))
        canvas.paste(top, (pfpbg.width, 0))
        canvas.paste(middle, (pfpbg.width, top.height))
        canvas.paste(bottom, (pfpbg.width, top.height + middle.height))
        draw = ImageDraw.Draw(canvas)
        if replied.sticker:
            replied.text = "Sticker"
        elif replied.photo:
            replied.text = "Photo"
        elif replied.audio:
            replied.text = "Audio"
        elif replied.voice:
            replied.text = "Voice Message"
        elif replied.document:
            replied.text = "Document"
        await replied_user(draw, reptot, replied.message.replace("\n", " "),
                           maxlength + len(title), len(title))
        y = 200
    elif reply.sticker:
        sticker = await reply.download_media()
        stimg = Image.open(sticker)
        canvas = canvas.resize(
            (stimg.width + pfpbg.width + 30, stimg.height + 10))
        canvas.paste(pfpbg, (0, 0))
        canvas.paste(stimg, (pfpbg.width + 10, 10))
        os.remove(sticker)
        return True, canvas
    elif reply.document and not reply.audio and not reply.audio:
        docname = ".".join(
            reply.document.attributes[-1].file_name.split(".")[:-1])
        doctype = reply.document.attributes[-1].file_name.split(
            ".")[-1].upper()
        if reply.document.size < 1024:
            docsize = str(reply.document.size) + " Bytes"
        elif reply.document.size < 1048576:
            docsize = str(round(reply.document.size / 1024, 2)) + " KB "
        elif reply.document.size < 1073741824:
            docsize = str(round(reply.document.size / 1024**2, 2)) + " MB "
        else:
            docsize = str(round(reply.document.size / 1024**3, 2)) + " GB "
        docbglen = font.getsize(docsize)[0] if font.getsize(
            docsize)[0] > font.getsize(docname)[0] else font.getsize(
                docname)[0]
        canvas = canvas.resize((pfpbg.width + width + docbglen, 160 + height))
        top, middle, bottom = await drawer(width + docbglen, height + 30)
        canvas.paste(pfpbg, (0, 0))
        canvas.paste(top, (pfpbg.width, 0))
        canvas.paste(middle, (pfpbg.width, top.height))
        canvas.paste(bottom, (pfpbg.width, top.height + middle.height))
        canvas = await doctype(docname, docsize, doctype, canvas)
        y = 80 if text else 0
    else:
        canvas.paste(pfpbg, (0, 0))
        canvas.paste(top, (pfpbg.width, 0))
        canvas.paste(middle, (pfpbg.width, top.height))
        canvas.paste(bottom, (pfpbg.width, top.height + middle.height))
        y = 85

    # Writing User's Name
    space = pfpbg.width + 30
    namefallback = ImageFont.truetype("resources/Quivira.otf",
                                      43,
                                      encoding="utf-16")
    for letter in tot:
        if letter in emoji.UNICODE_EMOJI:
            newemoji, mask = await emoji_fetch(letter)
            canvas.paste(newemoji, (space, 24), mask)
            space += 40
        else:
            if not await fontTest(letter):
                draw.text((space, 20), letter, font=namefallback, fill=color)
                space += namefallback.getsize(letter)[0]
            else:
                draw.text((space, 20), letter, font=font, fill=color)
                space += font.getsize(letter)[0]

    if title:
        draw.text((canvas.width - titlewidth - 20, 25),
                  title,
                  font=font2,
                  fill="#898989")

    # Writing all separating emojis and regular texts
    x = pfpbg.width + 30
    bold, mono, italic, link = await get_entity(reply)
    mdlength = 0
    index = 0
    emojicount = 0
    textfallback = ImageFont.truetype("resources/Quivira.otf",
                                      33,
                                      encoding="utf-16")
    textcolor = "white"
    for line in text:
        for letter in line:
            index = msg.find(
                letter) if emojicount == 0 else msg.find(letter) + emojicount
            for offset, length in bold.items():
                if index in range(offset, length):
                    font2 = ImageFont.truetype("resources/Roboto-Medium.ttf",
                                               33,
                                               encoding="utf-16")
                    textcolor = "white"
            for offset, length in italic.items():
                if index in range(offset, length):
                    font2 = ImageFont.truetype("resources/Roboto-Italic.ttf",
                                               33,
                                               encoding="utf-16")
                    textcolor = "white"
            for offset, length in mono.items():
                if index in range(offset, length):
                    font2 = ImageFont.truetype("resources/DroidSansMono.ttf",
                                               30,
                                               encoding="utf-16")
                    textcolor = "white"
            for offset, length in link.items():
                if index in range(offset, length):
                    font2 = ImageFont.truetype("resources/Roboto-Regular.ttf",
                                               30,
                                               encoding="utf-16")
                    textcolor = "#898989"
            if letter in emoji.UNICODE_EMOJI:
                newemoji, mask = await emoji_fetch(letter)
                canvas.paste(newemoji, (x, y - 2), mask)
                x += 45
                emojicount += 1
            else:
                if not await fontTest(letter):
                    draw.text((x, y),
                              letter,
                              font=textfallback,
                              fill=textcolor)
                    x += textfallback.getsize(letter)[0]
                else:
                    draw.text((x, y), letter, font=font2, fill=textcolor)
                    x += font2.getsize(letter)[0]
            msg = msg.replace(letter, "¶", 1)
        y += 40
        x = pfpbg.width + 30
    return True, canvas
Esempio n. 36
0
draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.
draw.rectangle((0, 0, width, height), outline=0, fill=(0, 0, 0))
disp.image(image)
# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height - padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0
# Alternatively load a TTF font.  Make sure the .ttf font file is in the
# same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
                          24)
big_font = ImageFont.truetype(
    '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 48)
small_font = ImageFont.truetype(
    '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 18)

font_height = font.getsize("a")[1]
big_font_height = big_font.getsize("a")[1]

red = "#FF0000"
green = "#00FF00"
blue = "#0000FF"
yellow = "#FFFF00"

# Turn on the backlight
backlight = digitalio.DigitalInOut(board.D22)
Esempio n. 37
0
def main(argc, argv):
    print("Preparing poster file...")

    font = ImageFont.truetype(FONT_TYPE, FONT_SIZE)
    rows = MAX_POKEMON_COUNT
    columns = MAX_POKEMON_COUNT

    startRow = 0
    startColumn = 0

    if argc == 2:
        columns, rows = [
            clamp(1, int(i), MAX_POKEMON_COUNT)
            if i.isnumeric() else MAX_POKEMON_COUNT for i in argv
        ]

    if argc == 4:
        startColumn, startRow = [
            clamp(0,
                  int(argv[i * 2]) -
                  1, MAX_POKEMON_COUNT) if argv[i * 2] else MAX_POKEMON_COUNT
            for i in range(2)
        ]
        columns, rows = [
            clamp(1, int(argv[i * 2 + 1]), MAX_POKEMON_COUNT)
            if argv[i * 2 + 1] else MAX_POKEMON_COUNT for i in range(2)
        ]

    background = Image.open("./Assets/background.png").convert("RGBA")
    finalW, finalH = (SPRITE_WIDTH * (columns + 1),
                      SPRITE_HEIGHT * (rows + 1) + BOTTOM_DELTA)
    final = Image.new("RGBA", (finalW, finalH))
    draw = ImageDraw.Draw(final)

    if not os.path.exists(MERGED_DIR):
        os.makedirs(MERGED_DIR)

    # Draw background first
    print("Adding background...")

    origin = Image.open("./Assets/origin.png").convert("RGBA")
    final.paste(origin, (0, 0, 340, 340))

    for i in range(columns + 1):
        for j in range(rows + 1):
            x, y = (i * SPRITE_WIDTH, j * SPRITE_HEIGHT)
            final.paste(background,
                        (x, y, x + SPRITE_WIDTH, y + SPRITE_HEIGHT))

    cellWidth = background.size[0]
    croppedCell = background.crop((0, 0, cellWidth, BOTTOM_DELTA))

    for i in range(columns + 1):
        x, y = (SPRITE_WIDTH * i, SPRITE_HEIGHT * (rows + 1))
        final.paste(croppedCell, (x, y, x + cellWidth, y + BOTTOM_DELTA))

    # Plop origin cell down

    origin = Image.open("./Assets/origin.png").convert("RGBA")
    final.paste(origin, (0, 0, 340, 340))

    # Draw sprites and text

    maxLineLength = 0

    for i in range(startColumn,
                   min(startColumn + columns, MAX_POKEMON_COUNT) + 1):
        for j in range(startRow, min(startRow + rows, MAX_POKEMON_COUNT) + 1):
            if not (i == startColumn and j == startRow):
                pokeName = ""
                fileName = ""
                body = 0
                face = 0
                red = 0

                if i == startColumn or j == startRow:
                    red = 255
                    index = j if i == startColumn else i
                    pokeName = POKEMON[index - 1]
                    text = "%03d. %s" % (index, pokeName)
                    body = index
                    face = index
                elif i == j:
                    red = 255
                    text = pokeName = POKEMON[i - 1]
                    body = face = i
                else:
                    body = i
                    face = j
                    text = pokeName = "%s%s" % (PREFIXES[j - 1],
                                                SUFFIXES[i - 1])

                print("Adding Sprite: (%03d,%03d)[%s].png" %
                      (body, face, pokeName))

                filename = "./Assets/Sprites/(%03d,%03d)[%s].png" % (
                    body, face, pokeName)
                current = Image.open(filename).convert("RGBA")

                x, y = (SPRITE_WIDTH * (i - startColumn),
                        SPRITE_HEIGHT * (j - startRow))
                width, height = current.size
                deltaX, deltaY = (round((SPRITE_WIDTH - width) / 2),
                                  round((SPRITE_HEIGHT - height) / 2))

                final.paste(current, (x + deltaX, y + deltaY,
                                      x + deltaX + width, y + deltaY + height),
                            current)

                w, h = draw.textsize(text, font=font)
                draw.text(
                    (x + (SPRITE_WIDTH - w) / 2, y + (SPRITE_HEIGHT - 33)),
                    text,
                    fill=(red, 0, 0, 255),
                    font=font)

    # Finally, draw credits

    credits = "「PokeFusion 2015 | Poster Generator: Alex Mueller | Sprites & Website: Alex Onsager @ https://pokemon.alexonsager.net」"
    f = ImageFont.truetype(FONT_TYPE, int(FONT_SIZE * 2 / 5))
    w, h = draw.textsize(credits, font=f)
    delta = (BOTTOM_DELTA - h) / 2
    x, y = ((finalW - w) / 2, finalH - h - delta)
    draw.text((x, y), credits, fill=(150, 150, 150, 255), font=f)

    print("Saving...", flush=True)
    final.save(
        '%s/PokeFusionsPoster(%ix%i)[rowStart=%s, columnStart=%s].png' %
        (MERGED_DIR, columns, rows, POKEMON[startRow], POKEMON[startColumn]))
    print("Finished!")
Esempio n. 38
0
# sunnyspeed studio
# YouTube: https://www.youtube.com/sunnyspeedstudio
# Purpose: Add timestamp on an image. The time information is retrived from image's exif.

from PIL import Image, ExifTags, ImageDraw, ImageFont
from pathlib import Path
import os
import sys

# config, feel free play around
text_font = ImageFont.truetype("DigitalTime.ttf", 160)
text_color = (255, 255, 255)
text_position = 'bottom_right'  # top_right, bottom_left, bottom_right
text_offset_x = 1200
text_offset_y = 200
subfolder = 'timestamp'


def getDateTime(image_file):
    img = Image.open(image_file)
    exif = dict(img.getexif())
    for key, value in exif.items():
        if key in ExifTags.TAGS:
            # print all exif info for debug
            # print(ExifTags.TAGS[key], value)
            if ExifTags.TAGS[key] == 'DateTimeOriginal':
                return value  # you may want to do some formatting on the datetime
            elif ExifTags.TAGS[key] == 'DateTimeDigitized':  # fallback
                return value
            elif ExifTags.TAGS[key] == 'DateTime':  # fallback
                return value
Esempio n. 39
0
def img_bottom_text_draw(pic_obj, exif):
    # get an image
    base_img = pic_obj.convert("RGBA")

    total_size = (base_img.size[0] + 20, base_img.size[1] + 40)

    base_layer = pillowImage.new("RGBA", total_size, (255, 255, 255, 0))

    # 计算位置和大小
    base_img_position = (10, 10)

    # draw logo
    base_layer.paste(base_img, box=base_img_position)

    # make a blank image for the text, initialized to transparent text color
    text_layer = pillowImage.new("RGBA", total_size, (255, 255, 255, 0))

    # get a font
    font_size = 19

    font_name = "NotoSansHans-Light.otf"
    # font_name = "NotoSansHans-Thin-Windows.otf"
    # font_name ="点点像素体-方形.ttf"

    text_font = ImageFont.truetype(font_name, font_size)

    # get a drawing context
    draw_obj = ImageDraw.Draw(text_layer)

    # set text color
    text_color = (
        0  # R
        ,
        0  # G
        ,
        0  # B
        ,
        255)  # A

    # draw date
    photo_date = exif['Exif.Photo.DateTimeOriginal'].split(" ")[0].replace(
        ":", "-")
    text_position = TextPosition.TextPosition("r", 10, "b", 10, 4, "right")
    text_xy = text_position.position(text_layer, photo_date, text_font)
    draw_obj.text(text_xy,
                  photo_date,
                  font=text_font,
                  fill=text_color,
                  align="right")

    # draw film type
    film = exif["Exif.Photo.UserComment"][14:]
    text_position = TextPosition.TextPosition("m", 0, "b", 10, 4, "center")
    text_xy = text_position.position(text_layer, film, text_font)
    draw_obj.text(text_xy,
                  film,
                  font=text_font,
                  fill=text_color,
                  align="center")

    # draw Camera
    camera = exif["Exif.Image.Model"]
    text_position = TextPosition.TextPosition("l", 10, "b", 10, 4, "right")
    text_xy = text_position.position(text_layer, camera, text_font)
    draw_obj.text(text_xy,
                  camera,
                  font=text_font,
                  fill=text_color,
                  align="right")

    # 后处理,与原始图像合并再转回RGB
    out = pillowImage.alpha_composite(base_layer, text_layer)
    out_jpg = out.convert('RGB')

    return out_jpg
Esempio n. 40
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
from escpos.printer import Usb
from escpos.constants import *

# font = ImageFont.truetype("Arial-Bold.ttf",14)
font = ImageFont.truetype("/home/francisco/gunplay3.ttf", 50)

precio = "$30.00"
codigo_barras = '1324354657687'
descripcion_producto = '123456789 123456789 123456789 123456789'


def generar_imagen_font(texto, fuente, filename):
    #Calcular el ancho y alto del font
    imgFont = Image.new("RGBA", (400, 200), (255, 255, 255))
    drawFont = ImageDraw.Draw(imgFont)
    WF, HF = drawFont.textsize(texto, font=fuente)
    deltaHF = int(round((HF * 0.40)))
    #Calcular el tamano del lienzo para dibujar
    W, H = (WF + 4, HF + deltaHF)
    img = Image.new("RGBA", (W, H), (255, 255, 255))
    draw = ImageDraw.Draw(img)
    #Dibujar el precio
    draw.text(((W - WF) / 2, 1), texto, (0, 0, 0), font=fuente)
    #Dibujar un recuadro dentro de la imagen.
Esempio n. 41
0
# 画直线
# drawAvatar = ImageDraw.Draw(im)
# xSize,ySize = im.size
#
# # 三等分位置
# drawAvatar.line([0, 0.33 * ySize, xSize, 0.33 * ySize],\
#     fill = (255, 100, 0), width = 3)
# # 左下角到中心点,右下角到中心点
# drawAvatar.line([(0, ySize), (0.5 * xSize, 0.5 * ySize), (xSize, ySize)],\
#     fill = (255, 0, 0), width = 3)
# im.save('image/5a2e2075f331d.jpg')

with Image.open("image/Hu.png").convert("RGBA") as base:

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

    # get a font
    fnt = ImageFont.truetype("C:\Windows\Fonts/Arial.ttf", 40)
    # get a drawing context
    d = ImageDraw.Draw(txt)

    # draw text, half opacity
    d.text((10, 10), "Hello", font=fnt, fill=(25, 255, 255, 128))
    # draw text, full opacity
    d.text((10, 60), "World", font=fnt, fill=(255, 25, 255, 255))

    out = Image.alpha_composite(base, txt)

    out.show()
Esempio n. 42
0
 def drawCompany(self, name):
     pos = (self.img.size[0] / 2, 700)
     font = ImageFont.truetype(self.ttfFont,
                               int(self.getFitSize(26, name) * 300 / 72))
     self.drawCenteredText(pos, name, (font, self.textColorCompany))
Esempio n. 43
0
from PIL import Image, ImageDraw, ImageFont

image_path = r'.\data\qq_avatar.png'
font_path = r'.\data\PeppaPigW07-Regular.ttf'
image_save_path = r'.\data\qq_avatar_numadded.png'
avatar = Image.open(image_path)
dr = ImageDraw.Draw(avatar)
# dr.line((0,0) + avatar.size, fill = 128, width=40)
# dr.line((0, avatar.size[1], avatar.size[0], 0), fill=128)
font = ImageFont.truetype(font_path, size=100)
dr.text((avatar.size[0] * 0.8, avatar.size[1] * 0.1),
        '4',
        font=font,
        fill=(230, 0, 0))
avatar.save(image_save_path)
Esempio n. 44
0
    def setConfig(self):
        global plaza, localidad, terminalEnt, pol, pol1, pol2, pol3, pol4, pol5, impresora, anchoPapel
        lenn = 0
        plaza = str(self.lno.text())
        localidad = str(self.llo.text())
        terminalEnt = str(self.le.text())
        impresora = int(self.cimpresora2.currentIndex())
        anchoPapel = int(self.cpapel2.currentIndex())

        pol1 = str(self.Lp1.toPlainText())
        pol2 = str(self.Lp2.toPlainText())
        pol3 = str(self.Lp3.toPlainText())
        pol4 = str(self.Lp4.toPlainText())
        pol5 = str(self.Lp5.toPlainText())
        pol = pol1 + pol2 + pol3 + pol4 + pol5

        image = Image.open('/home/pi/Documents/eum/app/expedidora/logo.png')
        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype(
            '/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed-Bold.ttf',
            size=16)

        (x, y) = (0, 40)
        message1 = plaza
        color = 'rgb(0, 0, 0)'  # black color
        draw.text((x, y), message1, fill=color, font=font)
        (x, y) = (0, 60)
        message2 = localidad
        draw.text((x, y), message2, fill=color, font=font)
        (x, y) = (0, 10)
        message3 = "¡BIENVENIDO!"
        font = ImageFont.truetype(
            '/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed-Bold.ttf',
            size=22)
        draw.text((x, y), message3, fill=color, font=font)
        image.save('/home/pi/Documents/eum/app/expedidora/logoPT.png')

        if (impresora == 0):
            #self.sustituye("/home/pi/.config/lxsession/LXDE-pi/autostart","@usr/bin/python3","@usr/bin/python3 /home/pi/Documents/eum/app/expedidora/firstMMM.py")
            self.sustituye(
                "/home/pi/.bashrc", "python3",
                "sudo python3 /home/pi/Documents/eum/app/expedidora/firstMMM.py"
            )
            if (anchoPapel == 1):
                lista = pol.split("\n")
                pol = ""
                for linea in lista:
                    lenn += 1
                    linea = "   " + linea + "\n"
                    pol = pol + linea
                    print(lenn, linea)
                print("POOOOL", pol)

            if (anchoPapel == 0):
                lista = pol.split("\n")
                pol = ""
                for linea in lista:
                    lenn += 1
                    linea = "" + linea + "\n"
                    pol = pol + linea
                    print(lenn, linea)
                print("POOOOL", pol)

            if (anchoPapel == 2):
                lista = pol.split("\n")
                pol = ""
                for linea in lista:
                    lenn += 1
                    linea = "              " + linea + "\n"
                    print(lenn, linea)
                    pol = pol + linea
                print("POOOOL", pol)
        else:
            self.sustituye(
                "/home/pi/.bashrc", "python3",
                "sudo python3 /home/pi/Documents/eum/app/expedidoraEpson/firstMMM.py"
            )

        print(plaza, localidad)
        dat = plaza + "," + localidad + "," + str(terminalEnt) + "," + str(
            impresora) + "," + str(anchoPapel)
        infile = open("/home/pi/Documents/eum/app/expedidora/datos.txt", 'w')
        c = infile.write(dat)

        infile.close()
        infile = open(
            "/home/pi/Documents/eum/app/expedidora/datos/Epsonpols.txt", 'w')
        c = infile.write(str(""))
        c = infile.write(str(pol))
        infile.close()
        infile = open(
            "/home/pi/Documents/eum/app/expedidora/datos/Epsonpols1.txt", 'w')
        c = infile.write(str(pol1))
        infile.close()
        infile = open(
            "/home/pi/Documents/eum/app/expedidora/datos/Epsonpols2.txt", 'w')
        c = infile.write(str(pol2))
        infile.close()
        infile = open(
            "/home/pi/Documents/eum/app/expedidora/datos/Epsonpols3.txt", 'w')
        c = infile.write(str(pol3))
        infile.close()
        infile = open(
            "/home/pi/Documents/eum/app/expedidora/datos/Epsonpols4.txt", 'w')
        c = infile.write(str(pol4))
        infile.close()
        infile = open(
            "/home/pi/Documents/eum/app/expedidora/datos/Epsonpols5.txt", 'w')
        c = infile.write(str(pol5))
        infile.close()

        self.datosEstacionamiento()
        self.cambia(1)
Esempio n. 45
0
    if os.path.exists(args.TLGAN_save_path):
        for file in glob.glob(args.TLGAN_save_path+"/*"):
            os.remove(file)

    if os.path.exists(args.CRNN_save_path):
        for file in glob.glob(args.CRNN_save_path + "/*"):
            os.remove(file)

    if is_simple:

        with open(os.path.join(args.text_file_path, args.text_file_name), 'r', encoding="utf-8") as textFile:
            lines = textFile.read().split("\n")[:n_simple]

            b, g, r = 255, 255, 255
            fontpath = "fonts/H2GTRM.TTF"
            font = ImageFont.truetype(fontpath, 20)

            if len(lines) <= n_text:
                tlgan, crnn = draw_image(lines, args.TLGAN_save_path, args.CRNN_save_path)
                tlgan_csv.update(tlgan)
                crnn_csv.update(crnn)

            else:
                for i in range(0, len(lines), n_text):
                    print(f"writing images ... {i}/{len(lines)} done")

                    if i + n_text >= len(lines):
                        tlgan, crnn = draw_image(lines[i:], args.TLGAN_save_path, args.CRNN_save_path)
                        tlgan_csv.update(tlgan)
                        crnn_csv.update(crnn)
                    else:
Esempio n. 46
0
def draw_bounding_box_on_image(image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               clss=None,
                               thickness=4,
                               display_str_list=(),
                               use_normalized_coordinates=True):
    """
    Adds a bounding box to an image.

    Bounding box coordinates can be specified in either absolute (pixel) or
    normalized coordinates by setting the use_normalized_coordinates argument.

    Each string in display_str_list is displayed on a separate line above the
    bounding box in black text on a rectangle filled with the input 'color'.
    If the top of the bounding box extends to the edge of the image, the strings
    are displayed below the bounding box.

    Args:
      image: a PIL.Image object.
      ymin: ymin of bounding box - upper left.
      xmin: xmin of bounding box.
      ymax: ymax of bounding box.
      xmax: xmax of bounding box.
      clss: the class of the object in this bounding box - will be cast to an int.
      thickness: line thickness. Default value is 4.
      display_str_list: list of strings to display in box
                        (each to be shown on its own line).
      use_normalized_coordinates: If True (default), treat coordinates
        ymin, xmin, ymax, xmax as relative to the image.  Otherwise treat
        coordinates as absolute.
    """
    if clss is None:
        color = COLORS[1]
    else:
        color = COLORS[int(clss) % len(COLORS)]

    draw = ImageDraw.Draw(image)
    im_width, im_height = image.size
    if use_normalized_coordinates:
        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                      ymin * im_height, ymax * im_height)
    else:
        (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
    draw.line([(left, top), (left, bottom), (right, bottom), (right, top),
               (left, top)],
              width=thickness,
              fill=color)

    try:
        font = ImageFont.truetype('arial.ttf', 32)
    except IOError:
        font = ImageFont.load_default()

    # If the total height of the display strings added to the top of the bounding
    # box exceeds the top of the image, stack the strings below the bounding box
    # instead of above.
    display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]
    # Each display_str has a top and bottom margin of 0.05x.
    total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)

    if top > total_display_str_height:
        text_bottom = top
    else:
        text_bottom = bottom + total_display_str_height

    # Reverse list and print from bottom to top.
    for display_str in display_str_list[::-1]:
        text_width, text_height = font.getsize(display_str)
        margin = np.ceil(0.05 * text_height)

        draw.rectangle([(left, text_bottom - text_height - 2 * margin),
                        (left + text_width, text_bottom)],
                       fill=color)
        draw.text((left + margin, text_bottom - text_height - margin),
                  display_str,
                  fill='black',
                  font=font)
        text_bottom -= (text_height + 2 * margin)
Esempio n. 47
0
    'LightGray', 'LightGrey', 'LightGreen', 'LightPink', 'LightSalmon',
    'LightSeaGreen', 'LightSkyBlue', 'LightSlateGray', 'LightSlateGrey',
    'LightSteelBlue', 'LightYellow', 'Lime', 'LimeGreen', 'Linen', 'Magenta',
    'MediumAquaMarine', 'MediumOrchid', 'MediumPurple', 'MediumSeaGreen',
    'MediumSlateBlue', 'MediumSpringGreen', 'MediumTurquoise',
    'MediumVioletRed', 'MintCream', 'MistyRose', 'Moccasin', 'NavajoWhite',
    'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed', 'Orchid',
    'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed',
    'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple',
    'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Green', 'SandyBrown',
    'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',
    'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue',
    'GreenYellow', 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat',
    'White', 'WhiteSmoke', 'Yellow', 'YellowGreen', 'LightBlue', 'LightGreen'
]
FONT = ImageFont.load_default()


def draw_a_rectangel_in_img(draw_obj, box, color, width, method):
    '''
    use draw lines to draw rectangle. since the draw_rectangle func can not modify the width of rectangle
    :param draw_obj:
    :param box: [x1, y1, x2, y2]
    :return:
    '''
    # color = (0, 255, 0)
    if method == 0:
        x1, y1, x2, y2 = box[0], box[1], box[2], box[3]
        top_left, top_right = (x1, y1), (x2, y1)
        bottom_left, bottom_right = (x1, y2), (x2, y2)
Esempio n. 48
0
                        os.path.join(dir1, type_,
                                     '{}:{}.png'.format(class_, extreme_)))
                    img2 = Image.open(
                        os.path.join(dir2, type_,
                                     '{}:{}.png'.format(class_, extreme_)))
                print(namespace)
            except FileNotFoundError:
                print('Images for {} do not exist!'.format(namespace))
                print(
                    os.path.join(dir1, type_,
                                 '{}:average-{}.png'.format(class_, extreme_)))
                continue
            new = Image.new(mode="RGB",
                            size=(max(img1.size[0], img2.size[0]) + 20,
                                  img1.size[1] + img2.size[1] + 400),
                            color=(255, 255, 255, 0))
            new.paste(img1, (10, 200))
            new.paste(img2, (10, img1.size[1] + 400))
            draw = ImageDraw.Draw(new)
            font = ImageFont.truetype("/home/marni/magisterka/arial.ttf", 35)
            # draw.text((x, y),"Sample Text",(r,g,b))
            draw.text((new.size[0] / 2 - 500, 50),
                      namespace + '- #1', (0, 0, 0),
                      font=font)
            draw.text((new.size[0] / 2 - 500, img1.size[1] + 200),
                      namespace + '- #2', (0, 0, 0),
                      font=font)
            new.save(
                os.path.join(outdir,
                             '{}_{}_{}.png'.format(type_, class_, extreme_)))
Esempio n. 49
0
                continue
    except:
        G_logger.error("Draw %s Failed" % section)
        return -1
    return img


if __name__ == '__main__':
    try:
        result_img = Image.new('RGBA', G_doc_size)
    except IOError:
        G_logger.error("Generate New Picture Failed")

    #字体字号
    info_font = ImageFont.truetype(
        (r'%spic\simsun.ttc' % G_path_prefix).decode('utf-8').encode('cp936'),
        15)
    #拼接图片
    high_count = 0
    try:
        for item in G_report_section:
            try:
                temp_img = draw_report(item, G_report_title, info_font)
            except:
                continue

            #将填好的部分贴入大图
            if temp_img != -1:
                result_img.paste(temp_img, (0, high_count))
                high_count = high_count + temp_img.size[1]
    except IOError:
Esempio n. 50
0
    gameboard = Image.open("Assets/background.png").convert('RGBA')

    # Add numbers
    for line in range(4):
        for case in range(4):
            if grid[line][case] is not None:
                coordinates = gridToCoordinates(line, case)
                # Open the case image
                block = Image.open(f"Assets/{grid[line][case]}.png").convert(
                    'RGBA')
                # Past
                gameboard.paste(block, coordinates, block)

    # Add the score
    myFont = ImageFont.truetype(font="Utils/arial.ttf", size=60)

    scoreImage = Image.open(f"Assets/score.png").convert('RGBA')
    message = str(score)
    draw = ImageDraw.Draw(scoreImage)
    w, h = draw.textsize(message, font=myFont)
    W, H = scoreImage.size
    draw.text(((W - w) / 2, (H - h + 40) / 2),
              message, (255, 255, 255),
              font=myFont)
    gameboard.paste(scoreImage, (599, 37), scoreImage)

    # Add the bestScore
    bestScoreImage = Image.open(f"Assets/best.png").convert('RGBA')
    message = str(bestScore)
    draw = ImageDraw.Draw(bestScoreImage)
Esempio n. 51
0
async def drawText(image_path, text):
    img = Image.open(image_path)
    os.remove(image_path)
    i_width, i_height = img.size
    if os.name == "nt":
        fnt = "arial.ttf"
    else:
        fnt = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
    m_font = ImageFont.truetype(fnt, int((70 / 640) * i_width))
    if ";" in text:
        upper_text, lower_text = text.split(";")
    else:
        upper_text = text
        lower_text = ""
    draw = ImageDraw.Draw(img)
    current_h, pad = 10, 5
    if upper_text:
        for u_text in textwrap.wrap(upper_text, width=15):
            u_width, u_height = draw.textsize(u_text, font=m_font)
            draw.text(
                xy=(((i_width - u_width) / 2) - 2,
                    int((current_h / 640) * i_width)),
                text=u_text,
                font=m_font,
                fill=(0, 0, 0),
            )
            draw.text(
                xy=(((i_width - u_width) / 2) + 2,
                    int((current_h / 640) * i_width)),
                text=u_text,
                font=m_font,
                fill=(0, 0, 0),
            )
            draw.text(
                xy=((i_width - u_width) / 2, int(
                    ((current_h / 640) * i_width)) - 2),
                text=u_text,
                font=m_font,
                fill=(0, 0, 0),
            )
            draw.text(
                xy=(((i_width - u_width) / 2),
                    int(((current_h / 640) * i_width)) + 2),
                text=u_text,
                font=m_font,
                fill=(0, 0, 0),
            )

            draw.text(
                xy=((i_width - u_width) / 2, int((current_h / 640) * i_width)),
                text=u_text,
                font=m_font,
                fill=(255, 255, 255),
            )
            current_h += u_height + pad
    if lower_text:
        for l_text in textwrap.wrap(lower_text, width=15):
            u_width, u_height = draw.textsize(l_text, font=m_font)
            draw.text(
                xy=(
                    ((i_width - u_width) / 2) - 2,
                    i_height - u_height - int((20 / 640) * i_width),
                ),
                text=l_text,
                font=m_font,
                fill=(0, 0, 0),
            )
            draw.text(
                xy=(
                    ((i_width - u_width) / 2) + 2,
                    i_height - u_height - int((20 / 640) * i_width),
                ),
                text=l_text,
                font=m_font,
                fill=(0, 0, 0),
            )
            draw.text(
                xy=(
                    (i_width - u_width) / 2,
                    (i_height - u_height - int((20 / 640) * i_width)) - 2,
                ),
                text=l_text,
                font=m_font,
                fill=(0, 0, 0),
            )
            draw.text(
                xy=(
                    (i_width - u_width) / 2,
                    (i_height - u_height - int((20 / 640) * i_width)) + 2,
                ),
                text=l_text,
                font=m_font,
                fill=(0, 0, 0),
            )

            draw.text(
                xy=(
                    (i_width - u_width) / 2,
                    i_height - u_height - int((20 / 640) * i_width),
                ),
                text=l_text,
                font=m_font,
                fill=(255, 255, 255),
            )
            current_h += u_height + pad
    image_name = "memify.webp"
    webp_file = os.path.join(Var.TEMP_DOWNLOAD_DIRECTORY, image_name)
    img.save(webp_file, "webp")
    return webp_file
Esempio n. 52
0
    def make_template(self, user, badge, template):
        """Build the base template before determining animated or not"""
        if hasattr(user, "roles"):
            department = (_("GENERAL SUPPORT") if user.top_role.name
                          == "@everyone" else user.top_role.name.upper())
            status = user.status
            level = str(len(user.roles))
        else:
            department = _("GENERAL SUPPORT")
            status = "online"
            level = "1"
        if str(status) == "online":
            status = _("ACTIVE")
        if str(status) == "offline":
            status = _("COMPLETING TASK")
        if str(status) == "idle":
            status = _("AWAITING INSTRUCTIONS")
        if str(status) == "dnd":
            status = _("MIA")
        barcode = BytesIO()
        temp_barcode = generate("code39",
                                str(user.id),
                                writer=ImageWriter(self),
                                output=barcode)
        barcode = Image.open(barcode)
        barcode = self.remove_white_barcode(barcode)
        fill = (0, 0, 0)  # text colour fill
        if badge.is_inverted:
            fill = (255, 255, 255)
            barcode = self.invert_barcode(barcode)
        template = Image.open(template)
        template = template.convert("RGBA")
        barcode = barcode.convert("RGBA")
        barcode = barcode.resize((555, 125), Image.ANTIALIAS)
        template.paste(barcode, (400, 520), barcode)
        # font for user information
        font_loc = str(bundled_data_path(self) / "arial.ttf")
        try:
            font1 = ImageFont.truetype(font_loc, 30)
            font2 = ImageFont.truetype(font_loc, 24)
        except Exception as e:
            print(e)
            font1 = None
            font2 = None
        # font for extra information

        draw = ImageDraw.Draw(template)
        # adds username
        draw.text((225, 330), str(user.display_name), fill=fill, font=font1)
        # adds ID Class
        draw.text((225, 400),
                  badge.code + "-" + str(user).split("#")[1],
                  fill=fill,
                  font=font1)
        # adds user id
        draw.text((250, 115), str(user.id), fill=fill, font=font2)
        # adds user status
        draw.text((250, 175), status, fill=fill, font=font2)
        # adds department from top role
        draw.text((250, 235), department, fill=fill, font=font2)
        # adds user level
        draw.text((420, 475), _("LEVEL ") + level, fill="red", font=font1)
        # adds user level
        if badge.badge_name != "discord" and user is discord.Member:
            draw.text((60, 585), str(user.joined_at), fill=fill, font=font2)
        else:
            draw.text((60, 585), str(user.created_at), fill=fill, font=font2)
        return template
Esempio n. 53
0
    return chr(random.randint(64, 90))


def rndColor():
    return (random.randint(64,
                           255), random.randint(64,
                                                255), random.randint(64, 255))


def rndColor2():
    return (random.randint(32,
                           127), random.randint(32,
                                                127), random.randint(32, 127))


width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))

font = ImageFont.truetype('arial.ttf', 36)
draw = ImageDraw.Draw(image)
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())

for t in range(4):
    draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())

image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
Esempio n. 54
0
    def get(self, request, *args, **kwargs):
        """
        获取验证码
        ---
        """
        uid = str(uuid.uuid4())
        mp_src = hashlib.md5(uid.encode("UTF-8")).hexdigest()
        text = mp_src[0:4]
        request.session["captcha_code"] = text
        request.session.save()
        font_path = current_path + "/www/static/www/fonts/Vera.ttf"
        logger.debug("======> font path " + str(font_path))
        font = ImageFont.truetype(font_path, 22)

        size = self.getsize(font, text)
        size = (size[0] * 2, int(size[1] * 1.4))

        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, '#001100')
            charimage = Image.new('L', self.getsize(font, ' %s ' % char),
                                  '#000000')
            chardraw = ImageDraw.Draw(charimage)
            chardraw.text((0, 0), ' %s ' % char, font=font, fill='#ffffff')
            if PIL_VERSION >= 116:
                charimage = charimage.rotate(random.randrange(*(-35, 35)),
                                             expand=0,
                                             resample=Image.BICUBIC)
            else:
                charimage = charimage.rotate(random.randrange(*(-35, 35)),
                                             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]))

        ImageDraw.Draw(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. 55
0
def make_wordcloud(words,
                   counts,
                   fname,
                   font_path=None,
                   width=400,
                   height=200,
                   margin=5,
                   ranks_only=False,
                   redraw_in_color=True):
    """Build word cloud using word counts, store in image.

    Parameters
    ----------
    words : numpy array of strings
        Words that will be drawn in the image.

    counts : numpy array of word counts
        Word counts or weighting of words. Determines the size of the word in
        the final image.
        Will be normalized to lie between zero and one.

    font_path : string
        Font path to the font that will be used.
        Defaults to DroidSansMono path.

    fname : sting
        Output filename. Extension determins image type
        (written with PIL).

    width : int (default=400)
        Width of the word cloud image.

    height : int (default=200)
        Height of the word cloud image.

    ranks_only : boolean (default=False)
        Only use the rank of the words, not the actual counts.

    Notes
    -----
    Larger Images with make the code significantly slower.
    If you need a large image, you can try running the algorithm at a lower
    resolution and then drawing the result at the desired resolution.

    In the current form it actually just uses the rank of the counts,
    i.e. the relative differences don't matter.
    Play with setting the font_size in the main loop vor differnt styles.

    Colors are used completely at random. Currently the colors are sampled
    from HSV space with a fixed S and V.
    Adjusting the percentages at the very end gives differnt color ranges.
    Obviously you can also set all at random - haven't tried that.

    """
    if len(counts) <= 0:
        print("We need at least 1 word to plot a word cloud, got %d." %
              len(counts))

    if font_path is None:
        font_path = FONT_PATH

    # normalize counts
    counts = counts / float(counts.max())
    # sort words by counts
    inds = np.argsort(counts)[::-1]
    counts = counts[inds]
    words = words[inds]
    # create image
    img_grey = Image.new("L", (width, height))
    draw = ImageDraw.Draw(img_grey)
    integral = np.zeros((height, width), dtype=np.uint32)
    img_array = np.asarray(img_grey)
    font_sizes, positions, orientations = [], [], []
    # intitiallize font size "large enough"
    font_size = 1000
    # start drawing grey image
    for word, count in zip(words, counts):
        # alternative way to set the font size
        if not ranks_only:
            font_size = min(font_size, int(100 * np.log(count + 100)))
        while True:
            # try to find a position
            font = ImageFont.truetype(font_path, font_size)
            # transpose font optionally
            orientation = random.choice([None, Image.ROTATE_90])
            transposed_font = ImageFont.TransposedFont(font,
                                                       orientation=orientation)
            draw.setfont(transposed_font)
            # get size of resulting text
            box_size = draw.textsize(word)
            # find possible places using integral image:
            result = query_integral_image(integral, box_size[1] + margin,
                                          box_size[0] + margin)
            if result is not None or font_size == 0:
                break
            # if we didn't find a place, make font smaller
            font_size -= 1

        if font_size == 0:
            # we were unable to draw any more
            break

        x, y = np.array(result) + margin // 2
        # actually draw the text
        draw.text((y, x), word, fill="white")
        positions.append((x, y))
        orientations.append(orientation)
        font_sizes.append(font_size)
        # recompute integral image
        img_array = np.asarray(img_grey)
        # recompute bottom right
        # the order of the cumsum's is important for speed ?!
        partial_integral = np.cumsum(np.cumsum(img_array[x:, y:], axis=1),
                                     axis=0)
        # paste recomputed part into old image
        # if x or y is zero it is a bit annoying
        if x > 0:
            if y > 0:
                partial_integral += (integral[x - 1, y:] -
                                     integral[x - 1, y - 1])
            else:
                partial_integral += integral[x - 1, y:]
        if y > 0:
            partial_integral += integral[x:, y - 1][:, np.newaxis]

        integral[x:, y:] = partial_integral

    if redraw_in_color:
        # redraw in color
        img = Image.new("RGB", (width, height))
        draw = ImageDraw.Draw(img)
        everything = zip(words, font_sizes, positions, orientations)
        for word, font_size, position, orientation in everything:
            font = ImageFont.truetype(font_path, font_size)
            # transpose font optionally
            transposed_font = ImageFont.TransposedFont(font,
                                                       orientation=orientation)
            draw.setfont(transposed_font)
            draw.text((position[1], position[0]),
                      word,
                      fill="hsl(%d" % random.randint(0, 255) + ", 80%, 50%)")
        img.show()
        img.save(fname)
    else:
        img_grey.show()
        img_grey.save(fname)
Esempio n. 56
0
from datetime import datetime
from PIL import Image, ImageColor, ImageFont, ImageDraw, ImageFilter

from Txt2img.generator import Generator
from Txt2img.transform import Rotate, Padding, GaussianNoise
from Txt2img.character import get_actually_used_hangul, get_english_alphabet

texts = ["아야어여오요우유으이가나다라마",
		"안녕하세요 저는 김기준입니다.",
		"테스트",
		"ㄴ미ㅏ엄니엄니ㅏ;어민어;민"]
path = "C:\\Users\\jwqe764241\\Desktop\\images"

generator = Generator(ImageFont.truetype(font="H2GTRE.TTF", size=30))

actually_used_hangul = get_actually_used_hangul()
english_alphabet = get_english_alphabet()

for i in range(len(texts)):
	image = generator.generate(texts[i], 'RGB', (0, 0, 0), (255, 255, 255),
	[
		Rotate(45, resample=Image.BILINEAR, expand=True, fillcolor=(255, 255, 255)),
		Padding(10, 10, 10, 10),
		GaussianNoise(0, 0.6)
	])
	dt = datetime.now()
	image.save(path + "\\" + dt.strftime("%Y.%m.%d %H.%M.%S.%f") + ".jpg", quality=100)

"""
for i in range(len(english_alphabet)):
#for i in range(1):
Esempio n. 57
0
libdir = join(dirname(dirname(realpath(__file__))), 'lib')

if exists(libdir):
    sys.path.append(libdir)

logging.basicConfig(level=logging.DEBUG)

try:
    logging.info("epd7in5 Demo")

    epd = epd7in5.EPD()
    logging.info("init and Clear")
    epd.init()
    epd.Clear()

    font24 = ImageFont.truetype(join(resdir, 'Font.ttc'), 24)
    font18 = ImageFont.truetype(join(resdir, 'Font.ttc'), 18)

    # Drawing on the Horizontal image
    logging.info("1.Drawing on the Horizontal image...")
    # 255: clear the frame
    Himage = Image.new('1', (epd.width, epd.height), 255)
    draw = ImageDraw.Draw(Himage)
    draw.text((10, 0), 'hello world', font=font24, fill=0)
    draw.text((10, 20), '7.5inch e-Paper', font=font24, fill=0)
    draw.text((150, 0), u'微雪电子', font=font24, fill=0)
    draw.line((20, 50, 70, 100), fill=0)
    draw.line((70, 50, 20, 100), fill=0)
    draw.rectangle((20, 50, 70, 100), outline=0)
    draw.line((165, 50, 165, 100), fill=0)
    draw.line((140, 75, 190, 75), fill=0)
Esempio n. 58
0
def uslugi(i):
    q = sql.internet_tv_us()
    font_size = 36
    width = 500
    height = 100
    back_ground_color = (255, 255, 255)
    font_size = 36
    font_size1 = 28
    font_color = (0, 0, 0)

    unicode_text = u"Услуга №1"
    unicode_text1 = u"Скорость:" + q[0][1]
    unicode_text2 = u"Каналы: " + q[0][2]
    unicode_text3 = q[0][3]
    unicode_text4 = q[0][4]
    unicode_text5 = q[0][0] + '%'
    image = Image.new('RGBA', (360, 480), 'white')
    draw = ImageDraw.Draw(image)
    draw.rectangle(((30, 250), (330, 280)), fill=(0, 0, 255))
    draw.rectangle(((32, 252), (328, 278)), fill=(255, 255, 255))
    draw.rectangle(((32, 252), (32 + int(q[0][1]), 278)), fill=(0, 255, 90))
    draw.ellipse([(140, 90), (230, 180)], fill=(255, 80, 0))
    draw.ellipse([(75, 330), (285, 390)], fill=(230, 230, 230))
    draw.ellipse([(75, 400), (285, 460)], fill=(0, 255, 70))
    unicode_font = ImageFont.truetype("DejaVuSans.ttf", font_size)
    unicode_font1 = ImageFont.truetype("DejaVuSans.ttf", font_size1)
    draw.text((30, 30), unicode_text, font=unicode_font, fill=font_color)
    draw.text((30, 200), unicode_text1, font=unicode_font, fill=font_color)
    draw.text((30, 280), unicode_text2, font=unicode_font, fill=font_color)
    draw.text((160, 340), unicode_text3, font=unicode_font1, fill=font_color)
    draw.text((160, 410), unicode_text4, font=unicode_font1, fill=font_color)
    draw.text((150, 112), unicode_text5, font=unicode_font, fill=font_color)
    image.save('sample.png')
    p = open('sample.png', 'rb')
    tgf_obj.bot.send_photo(i.message.chat.id, p)

    unicode_text = u"Услуга №2"
    unicode_text1 = u"Скорость:" + q[1][1]
    unicode_text2 = u"Каналы: " + q[1][2]
    unicode_text3 = q[1][3]
    unicode_text4 = q[1][4]
    unicode_text5 = q[1][0] + '%'
    image = Image.new('RGBA', (360, 480), 'white')
    draw = ImageDraw.Draw(image)
    draw.rectangle(((30, 250), (330, 280)), fill=(0, 0, 255))
    draw.rectangle(((32, 252), (328, 278)), fill=(255, 255, 255))
    draw.rectangle(((32, 252), (32 + int(q[1][1]), 278)), fill=(0, 255, 90))
    draw.ellipse([(140, 90), (230, 180)], fill=(255, 80, 0))
    draw.ellipse([(75, 330), (285, 390)], fill=(230, 230, 230))
    draw.ellipse([(75, 400), (285, 460)], fill=(0, 255, 70))
    unicode_font = ImageFont.truetype("DejaVuSans.ttf", font_size)
    unicode_font1 = ImageFont.truetype("DejaVuSans.ttf", font_size1)
    draw.text((30, 30), unicode_text, font=unicode_font, fill=font_color)
    draw.text((30, 200), unicode_text1, font=unicode_font, fill=font_color)
    draw.text((30, 280), unicode_text2, font=unicode_font, fill=font_color)
    draw.text((160, 340), unicode_text3, font=unicode_font1, fill=font_color)
    draw.text((160, 410), unicode_text4, font=unicode_font1, fill=font_color)
    draw.text((150, 112), unicode_text5, font=unicode_font, fill=font_color)
    image.save('sample.png')
    p = open('sample.png', 'rb')
    tgf_obj.bot.send_photo(i.message.chat.id, p)

    unicode_text = u"Услуга №3"
    unicode_text1 = u"Скорость:" + q[2][1]
    unicode_text2 = u"Каналы: " + q[2][2]
    unicode_text3 = q[2][3]
    unicode_text4 = q[2][4]
    unicode_text5 = q[2][0] + '%'
    image = Image.new('RGBA', (360, 480), 'white')
    draw = ImageDraw.Draw(image)
    draw.rectangle(((30, 250), (330, 280)), fill=(0, 0, 255))
    draw.rectangle(((32, 252), (328, 278)), fill=(255, 255, 255))
    draw.rectangle(((32, 252), (32 + int(q[2][1]), 278)), fill=(0, 255, 90))
    draw.ellipse([(140, 90), (230, 180)], fill=(255, 80, 0))
    draw.ellipse([(75, 330), (285, 390)], fill=(230, 230, 230))
    draw.ellipse([(75, 400), (285, 460)], fill=(0, 255, 70))
    unicode_font = ImageFont.truetype("DejaVuSans.ttf", font_size)
    unicode_font1 = ImageFont.truetype("DejaVuSans.ttf", font_size1)
    draw.text((30, 30), unicode_text, font=unicode_font, fill=font_color)
    draw.text((30, 200), unicode_text1, font=unicode_font, fill=font_color)
    draw.text((30, 280), unicode_text2, font=unicode_font, fill=font_color)
    draw.text((160, 340), unicode_text3, font=unicode_font1, fill=font_color)
    draw.text((160, 410), unicode_text4, font=unicode_font1, fill=font_color)
    draw.text((150, 112), unicode_text5, font=unicode_font, fill=font_color)
    image.save('sample.png')
    p = open('sample.png', 'rb')
    tgf_obj.bot.send_photo(i.message.chat.id, p)

    return States.INFO
Esempio n. 59
0
    color_pil = img_pil.convert("RGB")
    gray_pil = img_pil.convert("L")

    rect_arr = detect(gray_pil, FLAG_RECT)

    img_draw = ImageDraw.Draw(color_pil)
    colors = ['red', 'green', 'blue', "purple"]

    for i, rect in enumerate(rect_arr):
        x, y, w, h = rect
        for xy in [(x, y, x + w, y), (x + w, y, x + w, y + h),
                   (x + w, y + h, x, y + h), (x, y + h, x, y)]:
            img_draw.line(xy=xy, fill=colors[i % len(colors)], width=2)

    color_pil.show()
    color_pil.save("~color_pil.png")

    blank_pil = Image.new("L", img_pil.size, 255)
    blank_draw = ImageDraw.Draw(blank_pil)

    results = run(gray_pil)
    for i, line in enumerate(results):
        x, y, w, h = line[0]
        txt = line[1]
        print(i, txt)
        font = ImageFont.truetype("msyh.ttf", max(int(h * 0.6), 14))
        blank_draw.text(xy=(x, y), text=txt, font=font)

    blank_pil.show()
    blank_pil.save("~blank_pil.png")
Esempio n. 60
0
                    + (', {0}.{1}\'{2:.3f}"'.format(lon_deg, lon_min, lon_sec) + ew.printable))

#lat_lon_text = unicode(lat_lon_text).encode('utf-8', 'ignore')

print "Imagen: " + path_name, "..."
print "   EXIF GPS=", \
    lat_lon_text, "..."

im1 = Image.open(path_name)

draw = ImageDraw.Draw(im1)
#Mac OS X
#font = ImageFont.truetype(font='/Library/Fonts/Arial.ttf', size=75)

#Debian
font = ImageFont.truetype('/usr/share/fonts/truetype/msttcorefonts/arial.ttf',
                          size=75)

x = 5
y = 5

# thin border
draw.text((x - 1, y), lat_lon_text, font=font, fill='black')
draw.text((x + 1, y), lat_lon_text, font=font, fill='black')
draw.text((x, y - 1), lat_lon_text, font=font, fill='black')
draw.text((x, y + 1), lat_lon_text, font=font, fill='black')

# thicker border
draw.text((x - 1, y - 1), lat_lon_text, font=font, fill='black')
draw.text((x + 1, y - 1), lat_lon_text, font=font, fill='black')
draw.text((x - 1, y + 1), lat_lon_text, font=font, fill='black')
draw.text((x + 1, y + 1), lat_lon_text, font=font, fill='black')