示例#1
0
文件: core.py 项目: blundeln/drool
def writeProgressImage(value, range, file, text=None, warnThreshold=0.8):

    import PIL
    import Image, ImageDraw, ImageColor, ImageFont

    WIDTH = 100
    HEIGHT = 18

    def centerTextInBox(font, text, size):
        center = [0, 0]
        center[0] = size[0] / 2.0 - font.getsize(text)[0] / 2.0
        center[1] = size[1] / 2.0 - font.getsize(text)[1] / 2.0 + 1
        return center

    im = Image.new("RGBA", (WIDTH, HEIGHT))

    outline = ImageColor.getrgb("#000000")
    background = ImageColor.getrgb("#4697ff")
    bar = ImageColor.getrgb("#14ff00")
    barWarn = ImageColor.getrgb("#ff0f00")
    textColour = ImageColor.getrgb("#000000")

    try:
        percentage = float(value) / range
    except:
        percentage = 0.0

    if percentage > warnThreshold:
        barColour = barWarn
    else:
        barColour = bar
    barWidth = percentage * im.size[0]
    barWidth = min(barWidth, im.size[0])

    draw = ImageDraw.Draw(im)
    draw.rectangle([0, 0, im.size[0] - 1, im.size[1] - 1],
                   outline=outline,
                   fill=background)
    draw.rectangle([0, 0, barWidth - 1, im.size[1] - 1],
                   outline=outline,
                   fill=barColour)

    font = ImageFont.load_default()
    try:
        font = ImageFont.truetype("/var/tmp/Nimbus Sans L,", 16)
    except:
        debugOutput("Cannot load Nimbus font")
        font = ImageFont.load_default()
    if text:
        draw.text(centerTextInBox(font, text, im.size),
                  text,
                  font=font,
                  fill=textColour)

    if not drool.settings.options.testRun:
        im.save(file)
示例#2
0
文件: core.py 项目: blundeln/drool
def writeProgressImage(value, range, file, text=None, warnThreshold=0.8) :

  import PIL
  import Image, ImageDraw, ImageColor, ImageFont

  WIDTH = 100
  HEIGHT = 18

  def centerTextInBox(font, text, size) :
    center = [0,0]
    center[0] = size[0]/2.0 - font.getsize(text)[0]/2.0
    center[1] = size[1]/2.0 - font.getsize(text)[1]/2.0 + 1
    return center

  im = Image.new("RGBA",(WIDTH, HEIGHT))

  outline = ImageColor.getrgb("#000000")
  background = ImageColor.getrgb("#4697ff")
  bar = ImageColor.getrgb("#14ff00")
  barWarn = ImageColor.getrgb("#ff0f00")
  textColour = ImageColor.getrgb("#000000")

  try :
    percentage = float(value)/range
  except :
    percentage = 0.0

  if percentage > warnThreshold :
    barColour = barWarn
  else :
    barColour = bar
  barWidth = percentage * im.size[0]
  barWidth = min(barWidth, im.size[0])

  draw = ImageDraw.Draw(im)
  draw.rectangle([0,0, im.size[0]-1, im.size[1]-1], outline=outline, fill=background)
  draw.rectangle([0,0, barWidth-1, im.size[1]-1], outline=outline, fill=barColour)

  font = ImageFont.load_default()
  try :
    font = ImageFont.truetype("/var/tmp/Nimbus Sans L,",16)
  except :
    debugOutput("Cannot load Nimbus font")
    font = ImageFont.load_default()
  if text :
    draw.text(centerTextInBox(font, text, im.size), text, font=font, fill=textColour)

  if not drool.settings.options.testRun : 
    im.save(file)
示例#3
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()
示例#4
0
def _drawArrayText(d, data, x, y, values, scale=5, cCluster=(0, 0, 0), \
                    f = ImageFont.load_default()):
    """_drawClusteredArray(d, data, x, y, values, scale=5, cluster=(0, 0, 0))
    
    Draws the contents of the data array onto a given image.  Then writes the
    values given by the values array to the right hand side of the image.  
    There can only be upto two values in this array.
    """

    _drawArray(d, data, x, y, scale=scale, cCluster=cCluster)

    #Calculate text location
    sx = (data.shape[1] + 2) * scale
    th = data.shape[0] * scale

    #get font height
    fh = f.getsize("0.123")[1]

    if len(values) > 2:
        values = values[0:2]

    for v in range(len(values)):
        tmp = values[v]

        #Used to resolve a python underflow error returning negative 0.0
        if tmp == 0:
            tmp = abs(tmp)

        tmp = str(tmp)
        if len(tmp) > 5:
            tmp = tmp[0:5]
        d.text((sx, y + fh * v), tmp)
示例#5
0
    def _GenerateImage(self):
        # self._image = Image.new("RGB", self._IMAGESIZE, "white")

        # local vars
        # FontSize = 14
        # font = "Verdana.ttf"
        text = str(self._CurrentDirection)

        # font_dir = "/usr/share/fonts/truetype/msttcorefonts/"
        # font_size = FontSize
        # fnt = ImageFont.truetype(font_dir+font, font_size)
        fnt = ImageFont.load_default()
        lineWidth = 20
        bg = "#ffffff"

        img = Image.new("RGB", self._IMAGESIZE, "white")
        imgbg = Image.new("RGBA", img.size, "#000000")  # make an entirely black image
        mask = Image.new("L", img.size, "#000000")  # make a mask that masks out all
        draw = ImageDraw.Draw(img)  # setup to draw on the main image
        drawmask = ImageDraw.Draw(mask)  # setup to draw on the mask
        drawmask.line(
            (0, lineWidth / 2, img.size[0], lineWidth / 2), fill="#999999", width=10
        )  # draw a line on the mask to allow some bg through
        img.paste(imgbg, mask=mask)  # put the (somewhat) transparent bg on the main
        draw.text((10, 0), text, font=fnt, fill=bg)  # add some text to the main
        del draw

        self._image = img
示例#6
0
    def __blank_tile_default(self):
        import pkg_resources
        import Image as pil
        import ImageDraw
        import ImageFont

        im = pil.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()))
 def create_demo_photo(self, picture_name):
     target_path = os.path.join(self._photo_path, picture_name)
     image_width = 1200
     image_height = 800
     # Choose random colors
     green_color_value = random.random() * 0.8 + 0.2
     red_color_value = random.random() * 0.8 + 0.2
     blue_color_value = random.random() * 0.8 + 0.2
     image = Image.new("RGB", (image_width, image_height), 'black')
     draw = ImageDraw.Draw(image)
     # Draw gradient
     for x in range(image_width):
         for y in range(image_height):
             r = int(green_color_value * (x+1.0) / image_width * 255)
             g = int(red_color_value * (y+1.0) / image_height * 255)
             b = int(blue_color_value * (y+1.0) / (image_height + image_width / 2) * 255)
             color = (r, g, b)
             draw.point((x, y), fill=color)
     # Draw text
     try:
         font = ImageFont.truetype("ClientSideLib/OpenSans-Bold.ttf", 40)
     except IOError:
         font = ImageFont.load_default()
     draw.text(((image_width / 4), (image_height / 2 - 40)), picture_name, font=font)
     # Save image
     image.save(target_path, "JPEG")
示例#8
0
def write_tour_to_img(coords,tour,img_file):
    padding=20
    # shift all coords in a bit
    coords=[(x+padding,y+padding) for (x,y) in coords]
    maxx,maxy=0,0
    for x,y in coords:
        maxx=max(x,maxx)
        maxy=max(y,maxy)
    maxx+=padding
    maxy+=padding
    img=Image.new("RGB",(int(maxx),int(maxy)),color=(255,255,255))

    font=ImageFont.load_default()
    d=ImageDraw.Draw(img);
    num_cities=len(tour)
    for i in range(num_cities):
        j=(i+1)%num_cities
        city_i=tour[i]
        city_j=tour[j]
        x1,y1=coords[city_i]
        x2,y2=coords[city_j]
        d.line((int(x1),int(y1),int(x2),int(y2)),fill=(0,0,0))
        d.text((int(x1)+7,int(y1)-5),str(i),font=font,fill=(32,32,32))

    #for x,y in coords:
     #   x,y=int(x),int(y)
      #  d.ellipse((x-5,y-5,x+5,y+5),outline=(0,0,0),fill=(196,196,196))
    del d
    img.save(img_file, "PNG")
示例#9
0
def get_font(font_path, font_size):
    try:
        font = ImageFont.truetype(font_path, font_size)
    except IOError:
        font = ImageFont.load_default()

    return font
示例#10
0
    def draw_word_wrap(self,img, text, xpos=0, ypos=0, max_width=95):
        import Image,ImageDraw,ImageFont
        font=ImageFont.load_default()

        # textwrapping adapted from http://jesselegg.com/archives/2009/09/5/simple-word-wrap-algorithm-pythons-pil/

        draw = ImageDraw.Draw(img)
        text_size_x, text_size_y = draw.textsize(text, font=font)
        remaining = max_width
        space_width, space_height = draw.textsize(' ', font=font)
        # use this list as a stack, push/popping each line
        output_text = []
        # split on whitespace...
        for word in text.split(None):
            word_width, word_height = draw.textsize(word, font=font)
            if word_width + space_width > remaining:
                output_text.append(word)
                remaining = max_width - word_width
            else:
                if not output_text:
                    output_text.append(word)
                else:
                    output = output_text.pop()
                    output += ' %s' % word
                    output_text.append(output)
            remaining = remaining - (word_width + space_width)
        for text in output_text:
	    if(self.invertDisplay):
	      draw.text((xpos, ypos), text, font=font, fill='black')
	    else:
	      draw.text((xpos, ypos), text, font=font, fill='white')
            ypos += text_size_y
示例#11
0
def init_disp(rst):
    global image
    global draw
    global width
    global height
    global disp
    global font
    # 128x64 display with hardware I2C:
    disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(rst, GPIO.OUT)
    GPIO.output(rst, 1)
    disp.begin()
    # Clear display.
    disp.clear()
    disp.display()
    # Create blank image for drawing.
    # Make sure to create image with mode '1' for 1-bit color.
    width = disp.width
    height = disp.height
    image = Image.new('1', (width, height))
    # Get drawing object to draw on image.
    draw = ImageDraw.Draw(image)
    # Load default font.
    font = ImageFont.load_default()
示例#12
0
 def __init__(self, width, height):
     Renderer.__init__(self, width, height)
     import Image, ImageDraw, ImageFont
     self._pil_image = Image.new("RGB", (int(width), int(height)),
                                 (255, 255, 255))
     self._draw = ImageDraw.Draw(self._pil_image, "RGB")
     self._pil_font = ImageFont.load_default()
示例#13
0
def draw_text(image, text, horizontal_offset, vertical_offset,
              horizontal_justification, vertical_justification, size,
              color='#FFFFFF', orientation=None, font=None):
    """Draws text on an image."""
    image = convert_safe_mode(image)
    if orientation:
        orientation = getattr(Image, orientation)

    draw = ImageDraw.Draw(image)
    if font.strip():
        font = ImageFont.truetype(font, size)
    else:
        font = ImageFont.load_default()
        text = text.encode('ascii', 'replace')

    if orientation:
        font = ImageFont.TransposedFont(font, orientation)

    location = calculate_location(
        horizontal_offset, vertical_offset,
        horizontal_justification, vertical_justification,
        image.size, draw.textsize(text, font=font))

    # draw
    draw.text(location, text, font=font, fill=color)

    # composite the watermark with the layer
    return image
示例#14
0
    def _GenerateImage(self):
        #self._image = Image.new("RGB", self._IMAGESIZE, "white")

        # local vars
        #FontSize = 14
        #font = "Verdana.ttf"
        text = str(self._CurrentDirection)
                
        #font_dir = "/usr/share/fonts/truetype/msttcorefonts/"
        #font_size = FontSize
        #fnt = ImageFont.truetype(font_dir+font, font_size)
        fnt = ImageFont.load_default()
        lineWidth = 20
        bg="#ffffff"
        
        img = Image.new("RGB", self._IMAGESIZE, "white")
        imgbg = Image.new('RGBA', img.size, "#000000") # make an entirely black image
        mask = Image.new('L',img.size,"#000000")       # make a mask that masks out all
        draw = ImageDraw.Draw(img)                     # setup to draw on the main image
        drawmask = ImageDraw.Draw(mask)                # setup to draw on the mask
        drawmask.line((0, lineWidth/2, img.size[0],lineWidth/2),
                      fill="#999999", width=10)        # draw a line on the mask to allow some bg through
        img.paste(imgbg, mask=mask)                    # put the (somewhat) transparent bg on the main
        draw.text((10,0), text, font=fnt, fill=bg)      # add some text to the main
        del draw 
        
        self._image = img
示例#15
0
文件: character.py 项目: PP-TSD/sdgen
    def _get_font(self, font_type, size, typeface):
        """Get font with given parameters."""
        font_path = helpers.get_font_path(font_type, typeface)

        if font_path:
            return ImageFont.truetype(font_path, helpers.pt_to_px(size))
        return ImageFont.load_default()
示例#16
0
 def _draw_attribution(self, image, attribution, width, height):
     font = mod_imagefont.load_default()
     label_width, label_height = font.getsize(attribution)
     draw = mod_imagedraw.Draw(image)
     color = (255, 160, 0)
     draw.text((width - label_width, height - label_height), attribution,
               color, font)
示例#17
0
def generate_pattern(height, width, counter):
  """Generates an image that serves as a test pattern for encoding/decoding and
  accuracy tests."""

  retval = numpy.ndarray((3, height, width), dtype='uint8') 

  # standard color test pattern
  w = width / 7; w2 = 2*w; w3 = 3*w; w4 = 4*w; w5 = 5*w; w6 = 6*w
  retval[0,:,0:w]   = 255; retval[1,:,0:w]   = 255; retval[2,:,0:w]   = 255;
  retval[0,:,w:w2]  = 255; retval[1,:,w:w2]  = 255; retval[2,:,w:w2]  = 0;
  retval[0,:,w2:w3] = 0;   retval[1,:,w2:w3] = 255; retval[2,:,w2:w3] = 255;
  retval[0,:,w3:w4] = 0;   retval[1,:,w3:w4] = 255; retval[2,:,w3:w4] = 0;
  retval[0,:,w4:w5] = 255; retval[1,:,w4:w5] = 0;   retval[2,:,w4:w5] = 255;
  retval[0,:,w5:w6] = 255; retval[1,:,w5:w6] = 0;   retval[2,:,w5:w6] = 0;
  retval[0,:,w6:]   = 0;   retval[1,:,w6:]  = 0;   retval[2,:,w6:]   = 255;

  # black bar by the end
  h = height - height/4
  retval[:,h:,:] = 0

  try:
    # text indicating the frame number 

    import Image, ImageFont, ImageDraw
    text = 'frame #%d' % counter
    font = ImageFont.load_default()
    (text_width, text_height) = font.getsize(text)
    img = Image.fromarray(retval.transpose(1,2,0))
    draw = ImageDraw.Draw(img)
    draw.text((5, 5*height/6), text, font=font, fill=(255,255,255))
    retval = numpy.asarray(img).transpose(2,0,1)

  except ImportError, e:
    pass
示例#18
0
    def getfont(self):
        if not self.font:
            # FIXME: should add a font repository
            import ImageFont

            self.font = ImageFont.load_default()
        return self.font
示例#19
0
def label2img(labellist, height, fontname="helvR08.pil", imgformat="PNG", 
            fgcolor=(0,0,0), bgcolor=(255,255,255),
            rotate_angle=0):
	
    if exists(os.path.join(fontpath,fontname)):
    	font = ImageFont.load(os.path.join(fontpath,fontname))
    else:
	font = ImageFont.load_default()
    imgOut = Image.new("RGBA", (20,49), bgcolor)

    # calculate space needed to render text
    draw = ImageDraw.Draw(imgOut)
    sizex, sizey = draw.textsize(labellist[0], font=font)
    labelNum=len(labellist)

    imgOut = imgOut.resize((sizex,height*labelNum))
    draw = ImageDraw.Draw(imgOut)

    # render label into image draw area
    for i in range(labelNum):
    	draw.text((0, i*height), labellist[i], fill=fgcolor, font=font)

    if rotate_angle:
        imgOut = imgOut.rotate(rotate_angle)

    return imgOut
示例#20
0
def generateImage(price, currency, color):
    """Generate an Image object.
    
    price is a float, and currency is a three letter string
    to be shown after the price (e.g., 'BTC').
    
    To try to get better looking images, the original image
    is 4x larger and it is scaled down with antialiasing.
    """

    price_str = '{0:.4f} {1}'.format(price, currency)
    w, h = int(len(price_str) * 30 + 16), 56

    img = Image.new('RGBA', (w, h), (255, 255, 255, 0))

    draw = ImageDraw.Draw(img)
    try:
        font = ImageFont.truetype(FONT_PATH, 50)
    except:
        font = ImageFont.load_default()

    draw.text((0, 0), price_str, font=font, fill=color)
    img = img.resize((w/4, h/4), Image.ANTIALIAS)

    return img
示例#21
0
def get_font(fontpath):
    """Helper to find and return specified or default ImageFont."""
    if (fontpath):
        print "Found Font!"
        return ImageFont.truetype(fontpath, 14)
    else:
        return ImageFont.load_default()
示例#22
0
def get_font(fontpath):
    """Helper to find and return specified or default ImageFont."""
    if (fontpath):
        print "Found Font!"
        return ImageFont.truetype(fontpath, 14)
    else:
        return ImageFont.load_default()
示例#23
0
def make_centered_text(imageName, text, size=300, font=None, color=(0, 0, 0)):
    """
    Draws the text on an image.  If no font is provided, loads
    the default font.
    """

    ## 1. get the font, if no font available, load the
    ## default font
    if font == None:
        font = ImageFont.load_default()

    ## 2. create a new image with the white background
    im = Image.new('RGB', (size, size), 'white')

    ## 3. get ready to draw
    draw = ImageDraw.Draw(im)

    ## 4. figure out how big the text will be in the font
    sWidth, sHeight = font.getsize(text)

    ## 5. find the center of the image
    centerX = centerY = (size / 2 - 1)

    ## 6. find the position for the upper left corner of the text
    x = centerX - sWidth / 2
    y = centerY - sHeight / 2

    ## 7. draw the text
    draw.text((x, y), text, font=font, fill=color)
    del draw

    ## 8. save the image
    im.save(imageName)
    del im
示例#24
0
def draw_word_wrap(img, text, xpos=0, ypos=0, max_width=130,
                   fill=(0,0,0), font=ImageFont.load_default()):
    '''Draw the given ``text`` to the x and y position of the image, using
    the minimum length word-wrapping algorithm to restrict the text to
    a pixel width of ``max_width.``
    '''
    draw = ImageDraw.Draw(img)
    text_size_x, text_size_y = draw.textsize(text, font=font)
    remaining = max_width
    space_width, space_height = draw.textsize(' ', font=font)
    # use this list as a stack, push/popping each line
    output_text = []
    # split on whitespace...
    for word in text.split(None):
        word_width, word_height = draw.textsize(word, font=font)
        if word_width + space_width > remaining:
            output_text.append(word)
            remaining = max_width - word_width
        else:
            if not output_text:
                output_text.append(word)
            else:
                output = output_text.pop()
                output += ' %s' % word
                output_text.append(output)
            remaining = remaining - (word_width + space_width)
    for text in output_text:
        draw.text((xpos, ypos), text, font=font, fill=fill)
        ypos += text_size_y
示例#25
0
 def render(self, request):
     # Create a random 32 character string consisting of upper and lower case letters
     s = ''.join([random.choice(string.lowercase + string.uppercase) for x in xrange(32)])
     # Find the hash of the string
     s_hash = hashlib.sha1(s).hexdigest()
     # Load the font for the image
     font = ImageFont.load_default()
     # Find the width and height for the image
     text_width, text_height = font.getsize(s)
     # Create a blank image
     img = Image.new("RGB", (text_width, text_height), "#FFFFFF")
     # Draw the text on the image
     draw = ImageDraw.Draw(img)
     draw.text((0, 0), s, fill=(0, 0, 0))
     # Save the image in the webroot
     filename = s_hash + ".JPEG"
     file_path = os.path.join(request.webroot, filename)
     img.save(file_path, "JPEG")
     # HTML to send to the browser, showing the string image and text field
     content = """
     Type the following string in order to continue: <br>
     <img src="http://127.0.0.1/%s" />
     <br><br>
     <form action="http://127.0.0.1%s" method="post">
     <input type="text" name="strChar_text" size="50" maxlength="100">
     <input type="hidden" name="HashShouldBe" value="%s">
     <input type="hidden" name="host" value="%s"><br><br>
     <input type="submit" value="Submit" />
     </form>
     """ % (filename, request.path, s_hash, request.target_host)
     return content
示例#26
0
def init_disp(rst):
	global image
	global draw
	global width
	global height
	global disp
	global font
# 128x64 display with hardware I2C:
	disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
	GPIO.setmode(GPIO.BOARD)
	GPIO.setup(rst,GPIO.OUT)
	GPIO.output(rst,1)
	disp.begin()
# Clear display.
	disp.clear()
	disp.display()
# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
	width = disp.width
	height = disp.height
	image = Image.new('1', (width, height))
# Get drawing object to draw on image.
	draw = ImageDraw.Draw(image)
# Load default font.
	font = ImageFont.load_default()
示例#27
0
def __DrawCaptionWithPIL(imgPath, captionTxt):
    img = Image.open(imgPath)
    draw = ImageDraw.Draw(img)
    font = ImageFont.load_default()
    
    imgW = img.size[0]
    imgH = img.size[1]
    # print "IMG SIZE: %d x %d" % (imgW,imgH)
    txtSize = draw.textsize(captionTxt, font=font)
    # print "NAMESIZE: ",txtSize
    txtX = imgW/2 - (txtSize[0] / 2)
    txtY = imgH - (txtSize[1])
    
    draw.text((txtX,txtY), captionTxt, (0,0,0), font=font)

    # img.save('raspidentified.jpg')
    
    image = wx.EmptyImage(img.size[0],img.size[1])
    image.SetData(img.convert("RGB").tostring())
    image.SetAlphaData(img.convert("RGBA").tostring()[3::4])

    ## use the wx.Image or convert it to wx.Bitmap
    imgBmap = wx.BitmapFromImage(image)

    return imgBmap
示例#28
0
def make_centered_text(imageName, text, size = 300,
                      font = None, color = (0,0,0)):
    """
    Draws the text on an image.  If no font is provided, loads
    the default font.
    """

    ## 1. get the font, if no font available, load the
    ## default font
    if font == None:
        font = ImageFont.load_default()

    ## 2. create a new image with the white background
    im = Image.new('RGB', (size, size), 'white')

    ## 3. get ready to draw
    draw = ImageDraw.Draw(im)

    ## 4. figure out how big the text will be in the font
    sWidth, sHeight =  font.getsize(text)

    ## 5. find the center of the image
    centerX = centerY = (size/2 - 1)

    ## 6. find the position for the upper left corner of the text
    x = centerX - sWidth/2
    y = centerY - sHeight/2

    ## 7. draw the text
    draw.text((x,y), text, font = font, fill = color)
    del draw

    ## 8. save the image
    im.save(imageName)
    del im
示例#29
0
def get_font(font_path, font_size):
    try:
        font = ImageFont.truetype(font_path, font_size)
    except IOError:
        font = ImageFont.load_default()

    return font
示例#30
0
def drawData(imagex, imagey, gapx, gapy, cellx, celly, cells, cellshape, bgcolor, bdexist, bdcolor, printval):
	global dataset

	if exists(os.path.join(fontpath,"courR08.pil")):
	    font = ImageFont.load(os.path.join(fontpath,"courR08.pil"))
	else:
	    font = ImageFont.load_default()

	dataimg = Image.new("RGBA", (imagex,imagey), bgcolor)
	draw = ImageDraw.Draw(dataimg)

	for i in range(0,imagex,gapx):
		for j in range(0,imagey,gapy):
			color=getColor(dataset[j/gapy][i/gapx])
			x, y, z=color
			txcolor=(255-x, 255-y, 255-z)
			if cellshape == "rectangle":
				if bdexist == 'Y':
        				draw.rectangle([i, j, i+cellx,j+celly], outline=bdcolor, fill=color)
				else:
        				draw.rectangle([i, j, i+cellx,j+celly], fill=color)		
			else:
				if bdexist == 'Y':
					draw.ellipse([i, j, i+cellx,j+celly], outline=bdcolor ,fill=color)
				else:
        				draw.ellipse([i, j, i+cellx,j+celly], fill=color)		
			if(printval=="Y"):
				draw.text((i+cells,j+cells), dataset[j/gapy][i/gapx], fill=txcolor, font=font)

	return dataimg		
示例#31
0
def _drawArrayText(d, data, x, y, values, scale=5, cCluster=(0, 0, 0), \
                    f = ImageFont.load_default()):
    """_drawClusteredArray(d, data, x, y, values, scale=5, cluster=(0, 0, 0))
    
    Draws the contents of the data array onto a given image.  Then writes the
    values given by the values array to the right hand side of the image.  
    There can only be upto two values in this array.
    """
    
    _drawArray(d, data, x, y, scale=scale, cCluster=cCluster)
    
    #Calculate text location
    sx = (data.shape[1] + 2) * scale
    th = data.shape[0] * scale
    
    #get font height
    fh = f.getsize("0.123")[1]
    
    if len(values) > 2:
        values = values[0:2]
        
    for v in range(len(values)):
        tmp = values[v]
        
        #Used to resolve a python underflow error returning negative 0.0 
        if tmp == 0:
            tmp = abs(tmp)
            
        tmp = str(tmp)
        if len(tmp) > 5:
            tmp = tmp[0:5]
        d.text((sx, y + fh * v), tmp)
示例#32
0
def write_tour_to_img(coords, tour, img_file):
    padding = 20
    # shift all coords in a bit
    coords = [(x + padding, y + padding) for (x, y) in coords]
    maxx, maxy = 0, 0
    for x, y in coords:
        maxx = max(x, maxx)
        maxy = max(y, maxy)
    maxx += padding
    maxy += padding
    img = Image.new("RGB", (int(maxx), int(maxy)), color=(255, 255, 255))

    font = ImageFont.load_default()
    d = ImageDraw.Draw(img)
    num_cities = len(tour)
    for i in range(num_cities):
        j = (i + 1) % num_cities
        city_i = tour[i]
        city_j = tour[j]
        x1, y1 = coords[city_i]
        x2, y2 = coords[city_j]
        d.line((int(x1), int(y1), int(x2), int(y2)), fill=(0, 0, 0))
        d.text((int(x1) + 7, int(y1) - 5),
               str(i),
               font=font,
               fill=(32, 32, 32))

    #for x,y in coords:
    #   x,y=int(x),int(y)
    #  d.ellipse((x-5,y-5,x+5,y+5),outline=(0,0,0),fill=(196,196,196))
    del d
    img.save(img_file, "PNG")
示例#33
0
def draw_shapes(disp):
    # Initialize library.
    disp.begin()

    # Clear display.
    disp.clear()
    disp.display()

    # Create blank image for drawing.
    # Make sure to create image with mode '1' for 1-bit color.
    width = disp.width
    height = disp.height
    image = Image.new('1', (width, height))

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

    # Draw a black filled box to clear the image.
    draw.rectangle((0, 0, width, height), outline=0, fill=0)

    # Draw some shapes.
    # First define some constants to allow easy resizing of shapes.
    padding = 2
    shape_width = 20
    top = padding
    bottom = height - padding
    # Move left to right keeping track of the current x position for drawing shapes.
    x = padding
    # Draw an ellipse.
    draw.ellipse((x, top, x + shape_width, bottom), outline=255, fill=0)
    x += shape_width + padding
    # Draw a rectangle.
    draw.rectangle((x, top, x + shape_width, bottom), outline=255, fill=0)
    x += shape_width + padding
    # Draw a triangle.
    draw.polygon([(x, bottom), (x + shape_width / 2, top),
                  (x + shape_width, bottom)],
                 outline=255,
                 fill=0)
    x += shape_width + padding
    # Draw an X.
    draw.line((x, bottom, x + shape_width, top), fill=255)
    draw.line((x, top, x + shape_width, bottom), fill=255)
    x += shape_width + padding

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

    # Alternatively load a TTF font.
    # Some other nice fonts to try: http://www.dafont.com/bitmap.php
    #font = ImageFont.truetype('Minecraftia.ttf', 8)

    # Write two lines of text.
    draw.text((x, top), 'Hello', font=font, fill=255)
    draw.text((x, top + 15), 'World!', font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.display()
示例#34
0
def displayNum(draw, x, y, idx=0, num_pt=1, size=8): 
    try:
        font = ImageFont.truetype('/usr/share/fonts/dejavu/DejaVuSerif.ttf', int(size))
    except IOError:
        font = ImageFont.load_default()

    displayPoint(draw, x, y, idx, num_pt, radius=2.0)
    draw.text((x-3.0, y+3.0), str(idx), font=font)
示例#35
0
def displayNum(draw, x, y, idx=0, num_pt=1, size=8):
    try:
        font = ImageFont.truetype('/usr/share/fonts/dejavu/DejaVuSerif.ttf',
                                  int(size))
    except IOError:
        font = ImageFont.load_default()

    displayPoint(draw, x, y, idx, num_pt, radius=2.0)
    draw.text((x - 3.0, y + 3.0), str(idx), font=font)
示例#36
0
文件: Display.py 项目: Styku/htf
 def __init__(self):
     self.disp = Adafruit_SSD1306.SSD1306_128_64(rst=24)
     self.disp.begin()
     self.disp.clear()
     self.font = ImageFont.load_default()
     self.calib_image = [None]*18
     self.hexapod_image = Image.open('img/hexapod.ppm').convert('1')
     for i in range(18):       
         self.calib_image[i] = Image.open("img/hexapod%d.ppm" % (i+1)).convert('1')
示例#37
0
文件: Display.py 项目: Styku/htf
 def __init__(self):
     self.disp = Adafruit_SSD1306.SSD1306_128_64(rst=24)
     self.disp.begin()
     self.disp.clear()
     self.font = ImageFont.load_default()
     self.calib_image = [None] * 18
     self.hexapod_image = Image.open('img/hexapod.ppm').convert('1')
     for i in range(18):
         self.calib_image[i] = Image.open("img/hexapod%d.ppm" %
                                          (i + 1)).convert('1')
示例#38
0
 def setUp(self):
     """
     For this test suite, we will limit ourselves to crisp 
     black pixels (no anti-aliasing) on a white background.
     
     For converting images "in the wild" to this 
     format, see ink_test.py.
     """
     self.img = Image.new("1", (300, 200), "white")
     self.draw = ImageDraw.Draw(self.img)
     self.font = ImageFont.load_default()
    def __init__(self):
        # Raspberry Pi hardware SPI config:
        DC = 23
        RST = 24
        SPI_PORT = 0
        SPI_DEVICE = 0

        # Hardware SPI usage:
        self.display = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000))

        # Load default font.
        self.font = ImageFont.load_default()
示例#40
0
 def set_font(self, family, size):
     Renderer.set_font(self, family, size)
     import ImageFont
     try:
         self._pil_font = ImageFont.load(family + ".ttf", size)
     except Exception:
         import warnings
         warnings.warn("Could not load %s.ttf font!", stacklevel=2)
         try:
             self._pil_font = ImageFont.load("cour.ttf", size)
         except Exception:
             warnings.warn("Could not load the cour.ttf font!! Loading the default", stacklevel=2)
             self._pil_font = ImageFont.load_default()
示例#41
0
文件: snake.py 项目: dergigo/flipdots
def str2image(s):
    image = Image.new("1", (SIZE_X, SIZE_Y), PX[0])
    draw = ImageDraw.Draw(image)
    draw.fontmode = "1"         # No AA
    font = ImageFont.load_default()
    # font = ImageFont.truetype("FreeSans.ttf", FONT_SIZE)

    draw.text(FONT_OFFSET, s, font=font, fill=PX[1])

    imgmap = []
    for pixel in image.getdata():
        imgmap.append(pixel)

    return [imgmap[i*SIZE_X:i*SIZE_X+SIZE_X] for i in range(len(imgmap)/SIZE_X)]
示例#42
0
    def draw_labels_on_img(self, image_bytes, return_txt=True, **kwargs):
        image = Image.open(io.BytesIO(image_bytes))
        imgWidth, imgHeight = image.size
        draw = ImageDraw.Draw(image)
        response = self.predict_labels(image_bytes, **kwargs)
        # font = ImageFont.truetype('IBMPlexSans-Regular.ttf', size=15)
        font = ImageFont.load_default()
        cmap = cm.get_cmap('Paired')

        for idx, label in enumerate(response):
            name = label['Name']
            instances = label['Instances']
            color = colors.rgb2hex(cmap(idx)[:3])

            if len(instances) == 0: continue
            for instance in instances:
                confidence = instance['Confidence']
                box = instance['BoundingBox']
                left = imgWidth * box['Left']
                top = imgHeight * box['Top']
                width = imgWidth * box['Width']
                height = imgHeight * box['Height']

                points = (
                    (left, top),
                    (left + width, top),
                    (left + width, top + height),
                    (left, top + height),
                    (left, top),
                )

                # draw bounding box
                draw.rectangle([left, top, left + width, top + height],
                               outline=color,
                               width=2)

                # draw text
                text = f'{name} {int(confidence)}%'
                w, h = font.getsize(text)
                draw.rectangle([left, top, left + w, top + h], fill='black')
                draw.text(points[0], text, font=font, fill='white')

        if return_txt:
            txt = [
                '{} - {:.2f}%'.format(label['Name'], label['Confidence'])
                for label in response
            ]
            return image, txt
        else:
            return image
示例#43
0
def get_check_code_image(request):
    """
    background  #随机背景颜色
    line_color #随机干扰线颜色
    img_width = #画布宽度
    img_height = #画布高度
    font_color = #验证码字体颜色
    font_size = #验证码字体尺寸
    font = I#验证码字体
    """
    string = {'number':'12345679',
              'litter':'ACEFGHKMNPRTUVWXY'}
    background = (random.randrange(230,255),random.randrange(230,255),random.randrange(230,255))
    line_color = (random.randrange(0,255),random.randrange(0,255),random.randrange(0,255))
    img_width = 58
    img_height = 30
    font_color = ['black','darkblue','darkred']
    font_size = 14
    font = ImageFont.load_default()
    request.session['verify'] = ''

    #新建画布
    im = Image.new('RGB',(img_width,img_height),background)
    draw = ImageDraw.Draw(im)
    code = random.sample(string['litter'],4)
    #code  = u'和谐社会'
    #新建画笔
    draw = ImageDraw.Draw(im)

    #画干扰线
    for i in range(random.randrange(3,5)):
        xy = (random.randrange(0,img_width),random.randrange(0,img_height),
              random.randrange(0,img_width),random.randrange(0,img_height))
        draw.line(xy,fill=line_color,width=1)

    #写入验证码文字
    x = 2
    for i in code:
        y = random.randrange(0,10)
        draw.text((x,y), i, font=font, fill=random.choice(font_color))
        x += 14
        request.session['verify'] += i
    del x

    del draw
    buf = StringIO()
    im.save(buf,'gif')
    buf.seek(0)
    return HttpResponse(buf.getvalue(),'image/gif')
示例#44
0
def main():
    # initalize screen
    disp = setup_screen()
    # set up display
    image = Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT))
    draw = ImageDraw.Draw(image)
    #draw a white canvas
    draw.rectangle((0, 0, LCD.LCDWIDTH, LCD.LCDHEIGHT), outline=255, fill=255)
    # show some boot up text
    defaultfont = ImageFont.load_default()
    #font = ImageFont.truetype('/home/pi/mypi/fonts/v5prophit_cell/V5PRC___.TTF', 16)
    draw.text((8, 15), "Loading", font=defaultfont)
    disp.image(image)
    disp.display()
    location = 50
    for i in range(0, 3):
        draw.text((location, 15), ".", font=defaultfont)
        disp.image(image)
        disp.display()
        location += 5
        time.sleep(0.3)
    time.sleep(1)

    #set timezone to EST
    os.environ['TZ'] = 'US/Eastern'
    time.tzset()
    #clock loop
    while True:
        curtime = strftime("%I:%M:%S %p")
        weekday = strftime("%A")
        curdate = strftime("%b %d, %Y")
        disp.clear()
        draw.rectangle((0, 0, LCD.LCDWIDTH, LCD.LCDHEIGHT),
                       outline=255,
                       fill=255)
        # alarm check
        if (GPIO.input(alarmS) == False):
            draw.text((30, 32), "X", font=defaultfont)
            GPIO.output(buzzer, True)
        else:
            GPIO.output(buzzer, False)
        draw.text((1, 0), curtime, font=defaultfont)
        draw.text((1, 8), weekday, font=defaultfont)
        draw.text((1, 16), curdate, font=defaultfont)
        disp.image(image)
        disp.display()
        # exits script if button is pressed
        if (GPIO.input(exitB) == False):
            kill_clock(disp, image, draw)
示例#45
0
 def set_font(self, family, size):
     Renderer.set_font(self, family, size)
     import ImageFont
     try:
         self._pil_font = ImageFont.load(family + ".ttf", size)
     except Exception:
         import warnings
         warnings.warn("Could not load %s.ttf font!", stacklevel=2)
         try:
             self._pil_font = ImageFont.load("cour.ttf", size)
         except Exception:
             warnings.warn(
                 "Could not load the cour.ttf font!! Loading the default",
                 stacklevel=2)
             self._pil_font = ImageFont.load_default()
示例#46
0
文件: admin.py 项目: rossica/sukiyaki
    def ban_image(self, request, queryset):
        import Image, ImageDraw, ImageFont, os, stat
        replacement = Image.new("RGB", (128,128), "white")
        draw = ImageDraw.Draw(replacement)
        
        # generate a banned image
        try: 
            font = ImageFont.truetype("comicbd.ttf", 100)
            draw.text((0,0), "B&", font=font, fill="red")
        except: # in case the desired font is unavailable
            font = ImageFont.load_default()
            banned = "B&B&B&B&B&B&B&B&B&B&B&"
            draw.text((0,0), banned, font=font, fill="red")
            draw.text((0,10), banned, font=font, fill="red")
            draw.text((0,20), banned, font=font, fill="red")
            draw.text((0,30), banned, font=font, fill="red")
            draw.text((0,40), banned, font=font, fill="red")
            draw.text((0,50), banned, font=font, fill="red")
            draw.text((0,60), banned, font=font, fill="red")
            draw.text((0,70), banned, font=font, fill="red")
            draw.text((0,80), banned, font=font, fill="red")
            draw.text((0,90), banned, font=font, fill="red")
            draw.text((0,100), banned, font=font, fill="red")
            draw.text((0,110), banned, font=font, fill="red")
            draw.text((0,120), banned, font=font, fill="red")

        for post in queryset:
            img_path = os.path.join(MEDIA_ROOT, post.image.name)
            thumb_path = os.path.join(MEDIA_ROOT, post.thumbnail.name)
            path, filename = os.path.split(img_path)
            name, ext = os.path.splitext(filename)
            
            if img_path == thumb_path: # If the thumbnail and image are the same file, don't write twice (or assume the thumb is JPG)
                # Overwrite the offensive image with the banned image
                if os.stat(img_path).st_mode & stat.S_IWRITE: # file is writeable
                    replacement.save(img_path)
                    os.chmod(img_path, stat.S_IREAD) # Make read-only
            
            else: # The thumbnail and image are not the same file (safe to assume the thumbnail is JPG)
                # Overwrite the offensive image with the banned image
                if os.stat(img_path).st_mode & stat.S_IWRITE: # file is writeable
                    replacement.save(img_path)
                    os.chmod(img_path, stat.S_IREAD) # Make read-only
                    
                # Overwrite the offensive thumbnail with the banned image
                if os.stat(thumb_path).st_mode & stat.S_IWRITE: # thumb is writeable
                    replacement.save(thumb_path, optimize=True)
                    os.chmod(thumb_path, stat.S_IREAD) # make read-only
示例#47
0
def generate_montage(filenames):
    images = [Image.open(filename) for filename in filenames]

    width = 0
    height = 0
    i = 0
    sum_x = max_y = 0 
    width = max(image.size[1]+margin for image in images)*row_size
    height = sum(image.size[0]+margin for image in images)

    montage = Image.new(mode='RGBA', size=(width, height), color=(0,0,0,0))
    try:
        image_font = ImageFont.truetype('font/Helvetica.ttf', 18)
    except:
        try:
            image_font = ImageFont.load('font/Helvetica-18.pil')
        except:
            image_font = ImageFont.load_default()
    draw = ImageDraw.Draw(montage)
    offset_x = offset_y = 0

    i = 0
    max_y = 0
    max_x = 0
    offset_x = 0
    for image in images:
        montage.paste(image, (offset_x, offset_y))

        text_coords = offset_x + image.size[0] - 45, offset_y + 120
        draw.text(text_coords, '#{0}'.format(i+1), font=image_font)
        
        max_x = max(max_x, offset_x+image.size[0])
        if i % row_size == row_size-1: 
            offset_y += max_y+margin
            max_y = 0
            offset_x = 0
        else:
            offset_x += image.size[0]+margin
            max_y = max(max_y, image.size[1])

        i += 1

    if i % row_size:
        offset_y += max_y

    filename = strftime("Montage %Y-%m-%d at %H.%M.%S.png")
    montage = montage.crop((0, 0, max_x, offset_y))
    montage.save(filename)
def initOLED():
    global draw
    global disp
    global font
    global image
    disp.begin()
    # Clear display.
    disp.clear()
    disp.display()

    # Create blank image for drawing.
    # Make sure to create image with mode '1' for 1-bit color.
    width = disp.width
    height = disp.height
    image = Image.new('1', (width, height))

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

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)


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

    # Alternatively load a TTF font.
    # Some other nice fonts to try: http://www.dafont.com/bitmap.php
    #font = ImageFont.truetype('Minecraftia.ttf', 8)

    # Write two lines of text.
    draw.rectangle((0,0,width,height), outline=0, fill=0)
    disp.image(image)
    disp.display()

#    image = Image.open("MSGC.png")
#    image_r = image.resize((width,height),Image.BICUBIC)
#    image_bw = image_r.convert("1")
#
#    # Get drawing object to draw on image.
#    draw = ImageDraw.Draw(image)
#
#    for x in range(width):
#        for y in range (height):
#            disp.draw_pixel(x,y,bool(int(image_bw.getpixel((x,y)))))
#    disp.display()
#    time.sleep(1)
    return
def initOLED():
    global draw
    global disp
    global font
    global image
    disp.begin()
    # Clear display.
    disp.clear()
    disp.display()

    # Create blank image for drawing.
    # Make sure to create image with mode '1' for 1-bit color.
    width = disp.width
    height = disp.height
    image = Image.new('1', (width, height))

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

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)


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

    # Alternatively load a TTF font.
    # Some other nice fonts to try: http://www.dafont.com/bitmap.php
    #font = ImageFont.truetype('Minecraftia.ttf', 8)

    # Write two lines of text.
    draw.rectangle((0,0,width,height), outline=0, fill=0)
    disp.image(image)
    disp.display()

#    image = Image.open("MSGC.png")
#    image_r = image.resize((width,height),Image.BICUBIC)
#    image_bw = image_r.convert("1")
#
#    # Get drawing object to draw on image.
#    draw = ImageDraw.Draw(image)
#
#    for x in range(width):
#        for y in range (height):
#            disp.draw_pixel(x,y,bool(int(image_bw.getpixel((x,y)))))
#    disp.display()
#    time.sleep(1)
    return
示例#50
0
 def __init__(self):
     self._image = pilImage.new('RGB', (X, Y), colors[white])
     self._draw = ImageDraw.Draw(self._image)
     for font in 'Tahoma Verdana Arial Helvetica'.split():
         try:
             font = ImageFont.truetype(font + '.ttf', 12)
         except (AttributeError, IOError):
             font = None
         if font:
             break
     else:
         try:
             font = ImageFont.load_default()
         except (AttributeError, IOError):
             font = None
     self._font = font
示例#51
0
    def create_strs():
        '''''绘制验证码字符'''
        c_chars = get_chars()
        strs = '%s' % ''.join(c_chars)

        try:
            font = ImageFont.truetype(font_type, font_size)
        except:
            # 找不到指定字体就用默认的
            font = ImageFont.load_default().font
        font_width, font_height = font.getsize(strs)

        draw.text(((width - font_width) / 3, (height - font_height) / 4),
                  strs, font=font, fill=fg_color)

        return strs
def display(value):  # Code to display information to LCD
    # Load default font.
    font = ImageFont.load_default()

    # Alternatively load a TTF font.
    # Some nice fonts to try: http://www.dafont.com/bitmap.php
    # font = ImageFont.truetype('Minecraftia.ttf', 8)

    # Write some text.
    draw.text((8, 10), 'Heart Rate:', font=font)
    draw.text((17, 23), value, font=font)
    draw.text((40, 23), 'BPM', font=font)

    # Display image.
    disp.image(image)
    disp.display()
示例#53
0
文件: img.py 项目: wolfram2012/nimo
    def annotateLabel(self,point,label,color='red',mark=False, font=None, background=None):        
        '''
        Marks a point in the image with text 
        
        @param point: the point to mark as type Point
        @param label: the text to use as a string
        @param color: defined as ('#rrggbb' or 'name') 
        @param mark: of True or ['right', 'left', 'below', or 'above'] then also mark the point with a small circle
        @param font: An optional PIL.ImageFont font object to use. Alternatively, specify an integer and the label
        will use Arial font of that size. If None, then the default is used.
        @param background: An optional color that will be used to draw a rectangular background underneath the text.
        '''
        im = self.asAnnotated()
        draw = PIL.ImageDraw.Draw(im)
        if font == None:
            font = ImageFont.load_default()
        elif isinstance(font,int):
            font = ImageFont.truetype(pv.FONT_ARIAL, font)
        
        tw,th = draw.textsize(label, font=font)
            
        if background != None:
            point2 = pv.Point( point.x + tw, point.y+th)
            draw.rectangle([point.asTuple(), point2.asTuple()], fill=background)
            
        if mark in [True, 'right']:
            draw.text([point.X()+5,point.Y()-th/2],label,fill=color, font=font)
            box = [point.X()-3,point.Y()-3,point.X()+3,point.Y()+3]
            draw.ellipse(box,outline=color)
        elif mark in ['left']:
            draw.text([point.X()-tw-5,point.Y()-th/2],label,fill=color, font=font)
            box = [point.X()-3,point.Y()-3,point.X()+3,point.Y()+3]
            draw.ellipse(box,outline=color)
        elif mark in ['below']:
            draw.text([point.X()-tw/2,point.Y()+5],label,fill=color, font=font)
            box = [point.X()-3,point.Y()-3,point.X()+3,point.Y()+3]
            draw.ellipse(box,outline=color)
        elif mark in ['above']:
            draw.text([point.X()-tw/2,point.Y()-th-5],label,fill=color, font=font)
            box = [point.X()-3,point.Y()-3,point.X()+3,point.Y()+3]
            draw.ellipse(box,outline=color)
        else:
            draw.text([point.X(),point.Y()],label,fill=color, font=font)



        del draw
示例#54
0
    def __init__(self):
        '''
        Initializes the Adafruit SSD1306 library, the image object, and the font object.
        '''
        super(DisplayThread, self).__init__()
        # Initialize SSD1306 library
        global RST
        self._disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
        try:
            self._disp.begin()
        except:
            print("Error: I2C communication failed.")
            exit(-1)
        self._disp.clear()
        self._disp.display()

        # Create blank image for drawing
        # Make sure to create image with mode '1' for 1-bit color
        self.width = self._disp.width
        self.height = self._disp.height
        self._image = Image.new('1', (self.width, self.height))

        # Get drawing object to draw on image
        self._draw = ImageDraw.Draw(self._image)

        self.font = ImageFont.load_default()
        # wget http://www.geocities.jp/littlimi/arc/misaki/misaki_ttf_2015-04-10.zip
        #font = ImageFont.truetype('/home/pi/work/install/misakifont/misaki_gothic.ttf', font_size, encoding='unic')
        #font = ImageFont.truetype('/usr/share/fonts/truetype/roboto/Roboto-Light.ttf', font_size, encoding='unic')
        #font = ImageFont.truetype('fonts/8-bit_pusab.ttf', font_size, encoding='unic')
        #font = ImageFont.truetype('fonts/PrStart.ttf', font_size, encoding='unic')
        #font = ImageFont.truetype('fonts/PixelCharas.ttf', font_size, encoding='unic')

        # Calculate font width, height
        self.font_width, self.font_height = self.font.getsize("0")

        # Adjust font height if necessary (comment in)
        # font_height+=1

        # Message to be displayed (array of line string)
        self._lines = []

        # Condition object to notify update request
        self.update_request_condition = threading.Condition()

        # Flag to stop the main loop
        self._stopped = False
示例#55
0
def str2image(s):
    image = Image.new("1", (SIZE_X, SIZE_Y), PX[0])
    draw = ImageDraw.Draw(image)
    draw.fontmode = "1"  # No AA
    font = ImageFont.load_default()
    # font = ImageFont.truetype("FreeSans.ttf", FONT_SIZE)

    draw.text(FONT_OFFSET, s, font=font, fill=PX[1])

    imgmap = []
    for pixel in image.getdata():
        imgmap.append(pixel)

    return [
        imgmap[i * SIZE_X:i * SIZE_X + SIZE_X]
        for i in range(len(imgmap) / SIZE_X)
    ]
示例#56
0
def str2array(s):
    image = Image.new("RGBA", IMG_SIZE, C_BLACK)
    draw = ImageDraw.Draw(image)
    draw.fontmode = "1"         # No AA
    font = ImageFont.load_default()
    # font = ImageFont.truetype("FreeSans.ttf", FONT_SIZE)

    draw.text(FONT_OFFSET, s, font=font, fill=C_WHITE)

    imgmap = []
    for pixel in image.getdata():
        r, g, b, a = pixel
        if r == 255:
            imgmap.append(1)
        else:
            imgmap.append(0)
    return imgmap
示例#57
0
 def __init__(self):
     RST = 17
     DC = 27
     SPI_PORT = 0
     SPI_DEVICE = 0
     self.disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST,
                                                 dc=DC,
                                                 spi=SPI.SpiDev(SPI_PORT,
                                                                SPI_DEVICE,
                                                                max_speed_hz=8000000))
     self.disp.begin()
     self.disp.clear()
     self.disp.display()
     self.width = self.disp.width
     self.height = self.disp.height
     self.LINES = self.height / 8
     self.COLS = self.width / 6
     self.clear()
     self.font = ImageFont.load_default()
示例#58
0
 def set_font(self, family, size):
     Renderer.set_font(self, family, size)
     import ImageFont
     try:
         font_file = os.path.join(install_dir, "utils", family + ".ttf")
         if os.path.exists(font_file):
             self._pil_font = ImageFont.truetype(font_file, int(size))
         else:
             self._pil_font = ImageFont.truetype(family + ".ttf", int(size))
     except Exception:
         import warnings
         warnings.warn("Could not load %s.ttf font!", stacklevel=2)
         try:
             self._pil_font = ImageFont.truetype("cour.ttf", int(size))
         except Exception:
             warnings.warn(
                 "Could not load the cour.ttf font!! Loading the default",
                 stacklevel=2)
             self._pil_font = ImageFont.load_default()