Beispiel #1
0
    def test_load_path_not_found(self):
        # Arrange
        filename = "somefilenamethatdoesntexist.ttf"

        # Act/Assert
        with pytest.raises(IOError):
            ImageFont.load_path(filename)
        with pytest.raises(IOError):
            ImageFont.truetype(filename)
Beispiel #2
0
    def __init__(self, devnum=0, showVideoWindow=0):
        """devnum:  VideoCapture enumerates the available video capture devices
                    on your system.  If you have more than one device, specify
                    the desired one here.  The device number starts from 0.

           showVideoWindow: 0 ... do not display a video window (the default)
                            1 ... display a video window

                            Mainly used for debugging, since the video window
                            can not be closed or moved around.

        """
        self.dev = vidcap.new_Dev(devnum, showVideoWindow)
        self.normalfont = ImageFont.load_path('helvetica-10.pil')
        self.boldfont = ImageFont.load_path('helvB08.pil')
        self.font = None
Beispiel #3
0
    def __init__(self, devnum=0, showVideoWindow=0):
        """devnum:  VideoCapture enumerates the available video capture devices
                    on your system.  If you have more than one device, specify
                    the desired one here.  The device number starts from 0.

           showVideoWindow: 0 ... do not display a video window (the default)
                            1 ... display a video window

                            Mainly used for debugging, since the video window
                            can not be closed or moved around.

        """
        self.dev = vidcap.new_Dev(devnum, showVideoWindow)
        self.normalfont = ImageFont.load_path('helvetica-10.pil')
        self.boldfont = ImageFont.load_path('helvB08.pil')
        self.font = None
Beispiel #4
0
def get_font_handle(fontpath, *args):
    """Get a handle for a font path, caching the results"""

    # For Python 2, we want to make sure fontpath is a string, not unicode
    fontpath_str = six.ensure_str(fontpath) if fontpath is not None else None

    # Look for the font in the cache
    font_key = (fontpath_str, args)
    if font_key in get_font_handle.fontCache:
        return get_font_handle.fontCache[font_key]

    font = None
    if fontpath_str is not None:
        try:
            if fontpath_str.endswith('.ttf'):
                font = ImageFont.truetype(fontpath_str, *args)
            else:
                font = ImageFont.load_path(fontpath_str)
        except IOError:
            pass

    if font is None:
        font = ImageFont.load_default()
    if font is not None:
        get_font_handle.fontCache[font_key] = font
    return font
Beispiel #5
0
    def loadtitlefont(self):
        """Auxiliary method to load font if not yet done."""
        if self.titlefont == None:
#             print 'the bloody fonts dir is????', fontsdir
#             print 'pero esto que hace??', os.path.join(fontsdir, "courR18.pil")
#             /home/vital/Workspace/pyResources/Scientific_Lib/f2n_fonts/f2n_fonts/courR18.pil
#             /home/vital/Workspace/pyResources/Scientific_Lib/f2n_fonts
            self.titlefont = imft.load_path(os.path.join(fontsdir, "courR18.pil"))
Beispiel #6
0
def _pilFont(font):
	from PIL import ImageFont
	if font.pilfont:
		return font.pilfont
	if font.ttf and font.size and type(font.ttf) == StringType:
		try:
			if font.bold and font.italic:
				suffix = 'bi'
			elif font.bold:
				suffix = 'bd'
			elif font.italic:
				suffix = 'i'
			else:
				suffix = ''
			ttfpath = os.path.join(_truetypeprefix,'%s%s.ttf' % (font.ttf,suffix))
			pilfont = ImageFont.truetype(ttfpath,int(font.size))
			font._setfont(pilfont)
			return pilfont
		except:
			pilfont = ImageFont.truetype(os.path.join(_truetypeprefix,'arial.ttf'),int(font.size))
			font._setfont(pilfont)
			return pilfont
		
	if font.face: face = font.face
	else: face = 'times'

	size = _closestSize(font.size)
	if type(face) == StringType:
		try: 
			pilfont = ImageFont.load_path(_pilFontPath(face,size,font.bold))
		except:
			#print _pilFontPath(face,size,font.bold)
			return 0		# font not found!
	else:
		for item in font.face:
			pilfont = None
			try:
				pilfont = ImageFont.load_path(_pilFontPath(item,size,font.bold))
				break
			except: pass
		if pilfont == None: return 0	# font not found!
	font._setfont(pilfont)
	return pilfont
Beispiel #7
0
def cfg_read_font(fnt: str, sz: int) -> ImageFont:
    if fnt is None:
        return ImageFont.load_default()
    elif len(fnt) != 0 and fnt[0] == ':':
        return ImageFont.load_path(fnt)
    else:
        try:
            return ImageFont.truetype(fnt[1:], sz)
        except OSError:
            return ImageFont.FreeTypeFont(fnt[1:], size=sz)
Beispiel #8
0
def __draw_picture(file_path,
                   background_color=(255, 255, 255),
                   font_file=None,
                   **kwargs):
    # Get data from picture file
    with open(file_path) as f:
        data = f.read()

    # Create image object
    img = Image.new("RGBA", IMAGE_DIMENSIONS, background_color)
    draw = ImageDraw.Draw(img)

    # Load font file or set to None
    try:
        font = ImageFont.load_path(font_file)
    except AttributeError as e:
        font = None

    for l in data.split("\n"):
        # Ignore empty lines or comments
        if len(l) == 0 or l.startswith("#"):
            continue

        columns = l.split(" ")

        # Grab line number
        line_number = columns[0].replace(")", "")
        if len(line_number) > 1 and line_number[-1].isalpha():
            line_number = int(line_number[:-1])
        else:
            line_number = int(line_number)

        line_number = int(line_number)

        # Generate text for this line
        output = ""
        for c in columns[1:]:
            c = c.replace("sp", " ")
            try:
                output += c[-1] * int(c[:-1])
            except (IndexError, ValueError) as e:
                error_string = f'''Error parsing picture file "{file_path}"
    Line: {l}
    Character: "{c}"'''
                raise SystemExit(error_string)

        # Draw text
        __draw_line(draw, line_number, output, font, **kwargs)

    return img
Beispiel #9
0
def get_font_handle(fontpath, *args):
    
    font = None
    if fontpath is not None :
        try :
            if fontpath.endswith('.ttf'):
                font = ImageFont.truetype(fontpath, *args)
            else :
                font = ImageFont.load_path(fontpath)
        except IOError :
            pass
    
    if font is None :
        font = ImageFont.load_default()
        
    return font 
Beispiel #10
0
def load_PIL_font():
    global _PIL_font
    if _PIL_font:
        return _PIL_font
    for font_file in (
        "/usr/share/fonts/gnu-free/FreeMono.ttf",
        "/usr/share/fonts/liberation-mono/LiberationMono-Regular.ttf",
        ):
        if os.path.exists(font_file):
            try:
                _PIL_font = ImageFont.load_path(font_file)
                return _PIL_font
            except OSError:
                pass
    _PIL_font = ImageFont.load_default()
    return _PIL_font
Beispiel #11
0
def get_font_handle(fontpath, *args):
    font_key = (fontpath, args)
    if font_key in get_font_handle.fontCache:
        return get_font_handle.fontCache[font_key]
    font = None
    if fontpath is not None :
        try :
            if fontpath.endswith('.ttf'):
                font = ImageFont.truetype(fontpath, *args)
            else :
                font = ImageFont.load_path(fontpath)
        except IOError :
            pass
    
    if font is None :
        font = ImageFont.load_default()
    if font is not None :
        get_font_handle.fontCache[font_key] = font
    return font 
Beispiel #12
0
def get_font_handle(fontpath, *args):
    font_key = (fontpath, args)
    if font_key in get_font_handle.fontCache:
        return get_font_handle.fontCache[font_key]
    font = None
    if fontpath is not None :
        try :
            if fontpath.endswith('.ttf'):
                font = ImageFont.truetype(fontpath, *args)
            else :
                font = ImageFont.load_path(fontpath)
        except IOError :
            pass
    
    if font is None :
        font = ImageFont.load_default()
    if font is not None :
        get_font_handle.fontCache[font_key] = font
    return font 
Beispiel #13
0
def _getFonts():
	from PIL import ImageFont
	ttf = 'fonts/freefont/FreeSans.ttf'
	import sys, os
	for p in sys.path:
		path = os.path.join(p, ttf)
		if os.path.exists(path):
			break
	else:
		path = None
	if path:
		try:
			for size in range(16, 7, -1):
				fontList.append(ImageFont.truetype(path, size))
			return
		except ImportError:
			pass
	# no freetype font support
	for fontName in FontNameList:
		fontList.append(ImageFont.load_path(fontName))
Beispiel #14
0
def _getFonts():
    from PIL import ImageFont
    ttf = 'fonts/freefont/FreeSans.ttf'
    import sys, os
    for p in sys.path:
        path = os.path.join(p, ttf)
        if os.path.exists(path):
            break
    else:
        path = None
    if path:
        try:
            for size in range(16, 7, -1):
                fontList.append(ImageFont.truetype(path, size))
            return
        except ImportError:
            pass
    # no freetype font support
    for fontName in FontNameList:
        fontList.append(ImageFont.load_path(fontName))
Beispiel #15
0
 def load_font(self, name, path):
     self.fonts.set(name, ImageFont.load_path(path))
        def test_load_path_not_found(self):
            # Arrange
            filename = "somefilenamethatdoesntexist.ttf"

            # Act/Assert
            self.assertRaises(IOError, lambda: ImageFont.load_path(filename))
Beispiel #17
0
    def get_pilimage(self, bar_width):
        """Return the barcode as a PIL object"""

        show_label = self.options.get('show_label', True)

        # 11 bars per character, plus the stop
        num_bars = len(self.bars)

        log.debug("There are %d bars", num_bars)

        # Quiet zone is 10 bar widths on each side
        quiet_width = bar_width * 10

        fontsize = 0
        if show_label:
            default_fontsize = FONT_SIZES.get(bar_width, 24)
            fontsize = self.options.get('ttf_fontsize', default_fontsize)
            ttf_font = self.options.get('ttf_font')
            if ttf_font:
                font = ImageFont.truetype(ttf_font, fontsize)
            else:
                # Locate and load the font file relative to the module
                c128dir, _ = os.path.split(__file__)
                rootdir, _ = os.path.split(c128dir)

                fontfile = os.path.join(rootdir, "fonts",
                                        "courR%02d.pil" % fontsize)
                font = ImageFont.load_path(fontfile)

        # Total image width
        self.image_width = (2 * quiet_width) + (num_bars * bar_width)

        # Image height 30% of width
        label_border = self.options.get('label_border', 0)
        self.image_height = self.options.get('height') or (self.image_width /
                                                           3)
        bar_height = self.image_height - label_border - fontsize

        # Image: has a white background
        bottom_border = self.options.get('bottom_border', 0)
        img = Image.new('L',
                        (self.image_width, self.image_height + bottom_border),
                        255)

        class BarWriter:
            """Class which moves across the image, writing out bars"""
            def __init__(self, img, bar_height):
                self.img = img
                self.current_x = quiet_width
                if show_label:
                    self.symbol_top = int(quiet_width / 2)
                else:
                    self.symbol_top = 0
                self.bar_height = bar_height

            def write_bar(self, value):
                """Draw a bar at the current position,
                if the value is 1, otherwise move on silently"""

                # only write anything to the image if bar value is 1
                if value == 1:
                    for ypos in range(self.symbol_top, self.bar_height):
                        for xpos in range(self.current_x,
                                          self.current_x + bar_width):
                            img.putpixel((xpos, ypos), 0)
                self.current_x += bar_width

            def write_bars(self, bars):
                """write all bars to the image"""
                for bar in bars:
                    self.write_bar(int(bar))

        # draw the barcode bars themself
        writer = BarWriter(img, bar_height)
        writer.write_bars(self.bars)

        # Draw the text
        draw = ImageDraw.Draw(img)
        if show_label:
            xtextwidth = font.getsize(self.text)[0]
            xtextpos = self.image_width / 2 - (xtextwidth / 2)
            ytextpos = bar_height + label_border
            draw.text((xtextpos, ytextpos), self.text, font=font)
        return img
Beispiel #18
0
 def loadtitlefont(self):
     """Auxiliary method to load font if not yet done."""
     if self.titlefont is None:
         self.titlefont = imft.load_path(
             os.path.join(fontsdir, 'courR18.pil'))
Beispiel #19
0
    def get_pilimage(self, bar_width):
        def sum_len(total, item):
            """add the length of a given item to the total"""
            return total + len(item)

        num_bars = (7 * 12) + reduce(sum_len, self.guards, 0)

        quiet_width = bar_width * 9
        image_width = (2 * quiet_width) + (num_bars * bar_width)
        image_height = image_width / 2

        img = Image.new('L', (image_width, image_height), 255)

        class BarWriter:
            """Class which moves across the image, writing out bars"""
            def __init__(self, img):
                self.img = img
                self.current_x = quiet_width
                self.symbol_top = quiet_width / 2

            def write_bar(self, value, full=False):
                """Draw a bar at the current position,
                if the value is 1, otherwise move on silently"""

                # only write anything to the image if bar value is 1
                bar_height = int(image_height * (full and 0.9 or 0.8))
                if value == 1:
                    for ypos in range(self.symbol_top, bar_height):
                        for xpos in range(self.current_x,
                                          self.current_x + bar_width):
                            img.putpixel((xpos, ypos), 0)
                self.current_x += bar_width

            def write_bars(self, bars, full=False):
                """write all bars to the image"""
                for bar in bars:
                    self.write_bar(int(bar), full)

        # Draw the bars
        writer = BarWriter(img)
        writer.write_bars(self.guards[0], full=True)
        writer.write_bars(self.left_bars)
        writer.write_bars(self.guards[1], full=True)
        writer.write_bars(self.right_bars)
        writer.write_bars(self.guards[2], full=True)

        # Draw the text
        font_size = font_sizes.get(bar_width, 24)

        # Use relative name, PIL will do searching for us
        fontfile = os.path.join("fonts", "courR%02d.pil" % font_size)

        font = ImageFont.load_path(fontfile)
        draw = ImageDraw.Draw(img)
        draw.text((1 * bar_width, int(image_height * 0.7)),
                  self.code[0], font=font)
        draw.text((16 * bar_width, int(image_height * 0.8)),
                  self.code[1:7], font=font)
        draw.text((63 * bar_width, int(image_height * 0.8)), self.code[7:], font=font)
        self.width = image_width
        self.height = image_height
        return img
Beispiel #20
0
    def get_pilimage(self, bar_width):
        """Return the barcode as a PIL object"""

        show_label = self.options.get('show_label', True)

        # 11 bars per character, plus the stop
        num_bars = len(self.bars)

        log.debug("There are %d bars", num_bars)

        # Quiet zone is 10 bar widths on each side
        quiet_width = bar_width * 10

        fontsize = 0
        if show_label:
            default_fontsize = FONT_SIZES.get(bar_width, 24)
            fontsize = self.options.get('ttf_fontsize', default_fontsize)
            ttf_font = self.options.get('ttf_font')
            if ttf_font:
                font = ImageFont.truetype(ttf_font, fontsize)
            else:
                # Locate and load the font file relative to the module
                c128dir = os.path.dirname(os.path.realpath(__file__))
                rootdir, _ = os.path.split(c128dir)

                fontfile = os.path.join(
                    rootdir, "fonts", "courR%02d.pil" % fontsize)
                font = ImageFont.load_path(fontfile)

        # Total image width
        self.image_width = (2 * quiet_width) + (num_bars * bar_width)

        # Image height 30% of width
        label_border = self.options.get('label_border', 0)
        self.image_height = self.options.get('height') or (self.image_width / 3)
        bar_height = self.image_height - label_border - fontsize

        # Image: has a white background
        bottom_border = self.options.get('bottom_border', 0)
        img = Image.new('L', (
            self.image_width, int(self.image_height + bottom_border)), 255)

        class BarWriter:
            """Class which moves across the image, writing out bars"""
            def __init__(self, img, bar_height):
                self.img = img
                self.current_x = quiet_width
                if show_label:
                    self.symbol_top = quiet_width / 2
                else:
                    self.symbol_top = 0
                self.bar_height = bar_height

            def write_bar(self, value):
                """Draw a bar at the current position,
                if the value is 1, otherwise move on silently"""

                # only write anything to the image if bar value is 1
                if value == 1:
                    for ypos in range(int(self.symbol_top), int(self.bar_height)):
                        for xpos in range(self.current_x,
                                          self.current_x + bar_width):
                            img.putpixel((xpos, ypos), 0)
                self.current_x += bar_width

            def write_bars(self, bars):
                """write all bars to the image"""
                for bar in bars:
                    self.write_bar(int(bar))

        # draw the barcode bars themself
        writer = BarWriter(img, bar_height)
        writer.write_bars(self.bars)

        # Draw the text
        draw = ImageDraw.Draw(img)
        if show_label:
            xtextwidth = font.getsize(self.text)[0]
            xtextpos = self.image_width / 2 - (xtextwidth / 2)
            ytextpos = bar_height + label_border
            draw.text((xtextpos, ytextpos), self.text, font=font)
        return img
Beispiel #21
0
import SH1106
import utils as u

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont


## Init SPI
disp = SH1106.SH1106()
disp.Init()
disp.clear()

## Init fonts
try:
    font = ImageFont.load_path("courR08.pil")
except:
    font = ImageFont.load_default()

image = Image.new('1', (disp.width, disp.height), 1)
draw = ImageDraw.Draw(image)

def blank_display():
    draw.rectangle((0,0,disp.width-1,disp.height-1), outline=1, fill=1)

def show_display():
    disp.ShowImage(disp.getbuffer(image))


## Menu
padding = -2
Beispiel #22
0
 def loadinfofont(self):
     """Auxiliary method to load font if not yet done."""
     if self.infofont == None:
         self.infofont = imft.load_path(
             os.path.join(fontsdir, 'courR10.pil'))
Beispiel #23
0
from bitcoinrpc import AuthServiceProxy, JSONRPCException
from rgbmatrix import Adafruit_RGBmatrix


#############
# constants #
#############

# logs of bitcoin activity triggered by bitcoin.conf
rootdir = sys.path[0]
blockFile = rootdir + '/data/block_list.txt'
peerFile =  rootdir + '/data/peer_list.txt'
txFile =  rootdir + '/data/tx.txt'

# load font
font = ImageFont.load_path( rootdir + '/fonts/pilfonts/timR08.pil')

# brightness limits for random colors
DIM_MAX = 255
DIM_MED = 128
DIM_LOW = 100

# amount of time each LED row represents in seconds for block icons
TIMESCALE = 30

# maximum size of block in block info mode (in bytes)
MAX_BLOCKSIZE = 1000000

# block info number and thickness of block bars
BLOCK_BAR_HISTORY = 8
BLOCK_BAR_THICKNESS = 3
        def test_load_path_not_found(self):
            # Arrange
            filename = "somefilenamethatdoesntexist.ttf"

            # Act/Assert
            self.assertRaises(IOError, lambda: ImageFont.load_path(filename))
Beispiel #25
0
	def loadlabelfont(self):
		"""Auxiliary method to load font if not yet done."""
		if self.labelfont == None:
			self.labelfont = imft.load_path(os.path.join(fontsdir, "courR10.pil"))
Beispiel #26
0
	def loadlabelfont(self):
		"""Auxiliary method to load font if not yet done."""
		if self.labelfont == None:
			self.labelfont = imft.load_path(os.path.join(fontsdir, "courR10.pil"))
Beispiel #27
0
    def get_pilimage(self, bar_width):
        def sum_len(total, item):
            """add the length of a given item to the total"""
            return total + len(item)

        num_bars = (7 * 12) + reduce(sum_len, self.guards, 0)

        quiet_width = bar_width * 9
        image_width = (2 * quiet_width) + (num_bars * bar_width)
        image_height = image_width / 2

        img = Image.new('L', (image_width, image_height), 255)

        class BarWriter:
            """Class which moves across the image, writing out bars"""
            def __init__(self, img):
                self.img = img
                self.current_x = quiet_width
                self.symbol_top = quiet_width / 2

            def write_bar(self, value, full=False):
                """Draw a bar at the current position,
                if the value is 1, otherwise move on silently"""

                # only write anything to the image if bar value is 1
                bar_height = int(image_height * (full and 0.9 or 0.8))
                if value == 1:
                    for ypos in range(self.symbol_top, bar_height):
                        for xpos in range(self.current_x,
                                          self.current_x + bar_width):
                            img.putpixel((xpos, ypos), 0)
                self.current_x += bar_width

            def write_bars(self, bars, full=False):
                """write all bars to the image"""
                for bar in bars:
                    self.write_bar(int(bar), full)

        # Draw the bars
        writer = BarWriter(img)
        writer.write_bars(self.guards[0], full=True)
        writer.write_bars(self.left_bars)
        writer.write_bars(self.guards[1], full=True)
        writer.write_bars(self.right_bars)
        writer.write_bars(self.guards[2], full=True)

        # Draw the text
        font_size = font_sizes.get(bar_width, 24)

        # Use relative name, PIL will do searching for us
        fontfile = os.path.join("fonts", "courR%02d.pil" % font_size)

        font = ImageFont.load_path(fontfile)
        draw = ImageDraw.Draw(img)
        draw.text((1 * bar_width, int(image_height * 0.7)),
                  self.code[0],
                  font=font)
        draw.text((16 * bar_width, int(image_height * 0.8)),
                  self.code[1:7],
                  font=font)
        draw.text((63 * bar_width, int(image_height * 0.8)),
                  self.code[7:],
                  font=font)
        self.width = image_width
        self.height = image_height
        return img
Beispiel #28
0
from datetime import datetime
from bitcoinrpc import AuthServiceProxy, JSONRPCException
from rgbmatrix import Adafruit_RGBmatrix

#############
# constants #
#############

# logs of bitcoin activity triggered by bitcoin.conf
rootdir = sys.path[0]
blockFile = rootdir + '/data/block_list.txt'
peerFile = rootdir + '/data/peer_list.txt'
txFile = rootdir + '/data/tx.txt'

# load font
font = ImageFont.load_path(rootdir + '/fonts/pilfonts/timR08.pil')

# brightness limits for random colors
DIM_MAX = 255
DIM_MED = 128
DIM_LOW = 100

# amount of time each LED row represents in seconds for block icons
TIMESCALE = 30

# maximum size of block in block history mode (in bytes)
MAX_BLOCKSIZE = 2000000

# block info number and thickness of block bars
BLOCK_BAR_HISTORY = 8
BLOCK_BAR_THICKNESS = 3
Beispiel #29
0
def get_font(font_name, font_size):
    fontdir = os.path.dirname(os.path.abspath(__file__))
    fontfile = os.path.join(fontdir, "%s%02d.pil" % (font_name, font_size))
    font = ImageFont.load_path(fontfile)
    return font