Beispiel #1
1
class TextPen(Pen):
    '''For draw one line text on canvas '''
    font = PenParameter("font")
    font_size = PenParameter("font_size")
    text_interline_spacing = PenParameter("text_interline_spacing")
    fill_color = PenParameter("fill_color", export_filter=lambda c:c and Color(c))

    coordinates = PenParameter(
            'coordinates',
            validator=coordinates_validator,
            export_filter=Coordinates
            )
    text = PenParameter(
            "text",
            validator=bool,
            export_filter=lambda text: text.decode('utf8') \
                    if isinstance(text, str) else text
            )

    def __init__(self, config):
        super(TextPen, self).__init__(config)
        self.drawer = Drawing()
        for name, parameter in self.known_parameter.iteritems():
            if name not in ("text", "coordinates"):
                value = getattr(self, name)
                if value:
                    setattr(self.drawer, name, value)

    def draw(self, canvas):
        self.drawer.text(
                self.coordinates.x,
                self.coordinates.y,
                self.text.encode('utf8')
                )
        self.drawer.draw(canvas.image)
Beispiel #2
0
def wand1():
    """This is Python Wand example 1"""
    the_time = t.asctime()

    print "Importing image ", IFILE
    img_1 = Image(filename=IFILE)

    print "Cropping and resizing the image"
    img_1.crop(300, 0, width=300, height=282)
    img_1.resize(width=600, height=564)

    print "Creating a drawing and overlaying on it"
    draw = Drawing()

    draw.circle((100, 100), (120, 120))

    draw.rectangle(left=img_1.width-300, top=img_1.height-45, width=230,
               height=40, radius=5)

    draw.font_size = 17
    draw.fill_color = Color('white')
    draw.text_color = Color('white')
    draw.text(img_1.width-290, img_1.height-20, the_time)
    draw(img_1)

    print "Displaying, close the XTERM when done"
    display(img_1)
 def drawrect(self, row, col):
     draw = Drawing()
     draw.fill_color = Color('black')
     (x, y), (x2, y2) = self.pixel_box(row, col)
     for r in range(self.box_size):
         line_y = y + r
         draw.line((x, line_y), (x2, line_y))
         draw(self._img)
Beispiel #4
0
def replaceColorsInImage(img, color1, color2):
	ldraw = Drawing()
	ldraw.fill_color = color2
	width, height = img.size
	for x in range(0, width):
		for y in range(0, height):
			if img[x,y] == color1:
				ldraw.color(x, y, 'replace')
	ldraw(img)
def animate_slice(sliceviewer, name, start, end, filename, num_frames=10, font_size=24):
    """Generate an animated gif of a 2D slice moving through a third dimension.

    Args:
        sliceviewer (SliceViewer): A sliceviewer instance.
        name (str): The name of the third dimension to use.
        start (float): The starting value of the third dimension.
        end (float): The end value of the third dimension.
        filename (str): The file to save the gif to.

    Kwargs:
        num_frames (int): The number of frames the gif should contain.
        font_size: (int): The size of the caption.

    Example:
        ws = CreateMDWorkspace(3, Extents=[-10,10,-10,10,-10,10], Names=["X","Y","Z"], Units=["u","u","u"])
        FakeMDEventData(ws, PeakParams=[10000,0,0,0,1])
        sv = plotSlice(ws)
        #Resize and configure the slice viewer how you want the output to look
        sv.setNormalization(1) # We need to normalize by volume in this case, or the data won't show up
        #This will create a gif iterating from Z = -1 to Z = 1
        animate_slice(sv, "Z", -1, 1, "output.gif")
    """
    #Generate all the individual frames
    images = []
    for slice_point in numpy.linspace(start, end, num_frames):
        sliceviewer.setSlicePoint(name, slice_point)
        sliceviewer.refreshRebin()
        qimg = sliceviewer.getImage().toImage()
        data = QByteArray()
        buf = QBuffer(data)
        qimg.save(buf, "PNG")
        image = Image(blob=str(data))
        captionstrip_size = font_size + 10
        #To add whitespace to the top, we add a vertical border,
        #then crop out the bottom border
        image.border(Color("#fff"), 0, captionstrip_size)
        image.crop(0, 0, image.width, image.height - captionstrip_size)
        #Write the caption into the whitespace
        draw = Drawing()
        draw.font_size = font_size
        draw.text(5, font_size,"%s = %g" % (name,slice_point))
        draw(image)
        images.append(image)
    #Create a new image with the right dimensions
    animation = Image(width=images[0].width, height=images[0].height)
    #Copy in the frames from all the generated images
    for image in images:
        animation.sequence.append(image.sequence[0])
    #Drop the initial blank frame
    del animation.sequence[0]
    #Write the animation to disk
    animation.save(filename=filename)
def create_kernel(w=3, h=3):
	k = Image(width=w * kernel_size + 2, height=h * kernel_size + 2)
	
	draw = Drawing()
	draw.fill_color = Color("white")
	draw.stroke_color = Color("black")

	for y in xrange(0,h):
		for x in xrange(0,w):
			draw.rectangle(left=x*kernel_size, top=y*kernel_size,
							width=kernel_size, height=kernel_size)
			draw(k)

	return k
 def add_caption(self, name, quote):
     color = Color("white")
     draw = Drawing()
     draw.fill_color = Color("black")
     font = Font(path="impact.ttf", size=64, color=color)
     with Image(filename=name) as i:
         if "second" in quote:
             top = quote["first"]
             bottom = quote["second"]
             i.caption(text=top, font=font, gravity="north")
             i.caption(text=bottom, font=font, gravity="south")
         else:
             top = top = quote["first"]
             i.caption(text=top, font=font, gravity="north")
         i.save(filename=name)
Beispiel #8
0
def test_draw_alpha_user_error():
    with Drawing() as draw:
        with raises(TypeError):
            draw.alpha()
        with raises(TypeError):
            draw.alpha(1, 2, 4)
        with raises(ValueError):
            draw.alpha(1, 2, 'apples')
def draw_canvas():
    with Drawing() as draw:
        draw.fill_color = Color('transparent')
        #draw.fill_color = Color('white')
        draw.rectangle(left=0, top=0, width=bill_features['canvas'][0], height=bill_features['canvas'][1])
        with Image(width=bill_features['canvas'][0], height=bill_features['canvas'][1]) as img:
            draw.draw(img)
            img.save(filename=bill_file)
Beispiel #10
0
def test_draw_point():
    with nested(Color('#fff'), Color('#000')) as (white, black):
        with Image(width=5, height=5, background=white) as img:
            with Drawing() as draw:
                draw.stroke_color = black
                draw.point(2, 2)
                draw.draw(img)
                assert img[2, 2] == black
Beispiel #11
0
 def test_imagesize(self):
     with Drawing() as d:
         text = 'check'
         d.font = 'Arial'
         d.font_size = 36
         size = calcSuitableImagesize(d, text)
         print('calcSuitableImagesize: ', size)
         self.assertTrue(size[0] > 0 and size[1] > 0)
Beispiel #12
0
 def __init__(self, config):
     super(TextPen, self).__init__(config)
     self.drawer = Drawing()
     for name, parameter in self.known_parameter.iteritems():
         if name not in ("text", "coordinates"):
             value = getattr(self, name)
             if value:
                 setattr(self.drawer, name, value)
Beispiel #13
0
def test_draw_alpha():
    with nested(Color('#fff'), Color('transparent')) as (white, transparent):
        with Image(width=50, height=50, background=white) as img:
            with Drawing() as draw:
                draw.fill_opacity = 0
                draw.alpha(25, 25, 'floodfill')
                draw.draw(img)
                assert img[25, 25] == transparent
Beispiel #14
0
def test_draw_matte_user_error():
    with Drawing() as draw:
        with raises(TypeError):
            draw.matte()
        with raises(TypeError):
            draw.matte(1, 2, 4)
        with raises(ValueError):
            draw.matte(1, 2, 'apples')
Beispiel #15
0
def test_clone_drawing_wand(fx_wand):
    fx_wand.text_kerning = 10.22
    funcs = (lambda img: Drawing(drawing=fx_wand),
             lambda img: fx_wand.clone())
    for func in funcs:
        with func(fx_wand) as cloned:
            assert fx_wand.resource is not cloned.resource
            assert fx_wand.text_kerning == cloned.text_kerning
Beispiel #16
0
 def draw_rectangle(self, x, y, width, height):  # pragma: no cover
     """draw_rectangle is used only in `/debug` routes"""
     with Drawing() as draw:
         draw.fill_color = "transparent"
         draw.stroke_color = "white"
         draw.stroke_width = 1
         draw.rectangle(x, y, width=width, height=height)
         draw(self.image)
Beispiel #17
0
def test_draw_alpha():
    transparent = Color('transparent')
    with Image(width=50, height=50, pseudo='xc:white') as img:
        with Drawing() as draw:
            draw.fill_color = transparent
            draw.alpha(25, 25, 'floodfill')
            draw.draw(img)
        assert img[25, 25] == transparent
Beispiel #18
0
def layer03():
    draw = Drawing()
    draw.font = FONT_HAIRLINE
    draw.font_size = 69
    draw.fill_color = Color('white')
    draw.text(0, 69, "Liam Mulcahy")

    draw.font = FONT_LIGHT
    draw.font_size =50 
    draw.text(0, 125, "Our next Einstein?")
 
    req_width = 570
    req_height = 130
    blurb_image = new_blank_png(req_width, req_height)
    draw(blurb_image)

    return blurb_image
Beispiel #19
0
def test_draw_push_pop():
    with Drawing() as draw:
        draw.stroke_width = 2
        draw.push()
        draw.stroke_width = 3
        assert 3 == draw.stroke_width
        draw.pop()
        assert 2 == draw.stroke_width
Beispiel #20
0
def test_draw_comment():
    comment = 'pikachu\'s ghost'
    expected = '#pikachu\'s ghost\n'
    with nested(Image(width=1, height=1), Drawing()) as (img, draw):
        draw.comment(comment)
        draw(img)
        blob = img.make_blob(format="mvg")
        assert expected == text(blob)
Beispiel #21
0
def test_draw_color():
    with nested(Color('#fff'), Color('#000')) as (white, black):
        with Image(width=50, height=50, background=white) as img:
            with Drawing() as draw:
                draw.fill_color = black
                draw.color(25, 25, 'floodfill')
                draw.draw(img)
                assert img[25, 25] == black
Beispiel #22
0
def test_draw_color_user_error():
    with Drawing() as draw:
        with raises(TypeError):
            draw.color()
        with raises(TypeError):
            draw.color(1, 2, 4)
        with raises(ValueError):
            draw.color(1, 2, 'apples')
Beispiel #23
0
def render_text(
    img,
    text,
    font,
    *,
    antialias=True,
    padding=0,
    color="black",
    font_size_hint=12
):
    """ renders a text as large as possible on a provided image

    :param wand.image.Image img: a wand.image.Image instance
    :param str text: the text to render
    :param str font: path to a font file to use

    optional:
    :param bool antialias: use antialiasing, defaults to True
    :param int padding: padding to apply to the image for the text rendering
    :param str color: text color to use
    :param int font_size_hint: font
        size used as a starting point for the search of the largest font size,
        also used for finding the best way to wrap a text.
    :returns RenderingFit: parameters used to render the text on the image
    """

    box_size = Size(img.width - 2 * padding, img.height - 2 * padding)

    with Drawing() as sketch:
        # Set the basic font style
        sketch.fill_color = Color(color)
        sketch.font = font
        sketch.font_size = font_size_hint
        sketch.text_antialias = antialias

        # search for the largest font size to render the text inside the box
        best_fit = find_best_text_fit(sketch, img, box_size, text)
        sketch.font_size = best_fit.font_size

        # calculate the positioning of the text in the image
        # the y value used in sketch.text() method to render the text
        # specifies the baseline of the first line of text
        # this must be adjusted with the character height of the text
        x = (box_size.width - best_fit.width) // 2
        unadjusted_y = (box_size.height - best_fit.height) // 2
        y = unadjusted_y + best_fit.character_height

        # render the text and  return the image
        sketch.text(x, int(y), "\n".join(best_fit.lines))
        sketch.draw(img)

        return RenderingFit(
            lines=best_fit.lines,
            font_size=best_fit.font_size,
            x=int(x),
            y=int(y),
            character_height=best_fit.character_height,
        )
Beispiel #24
0
def display_bounding_boxes_within_notebook(page_num,
                                           extractor,
                                           blocks,
                                           alternatecolors=False,
                                           color=Color('blue')):
    """
    Displays each of the bounding boxes passed in 'boxes' on an image of the pdf
    pointed to by pdf_file
    boxes is a list of 5-tuples (page, top, left, bottom, right)
    """
    elems = extractor.elems[page_num]
    page_width, page_height = int(elems.layout.width), int(elems.layout.height)
    img = pdf_to_img(extractor.pdf_file, page_num, page_width, page_height)
    draw = Drawing()
    draw.fill_color = Color('rgba(0, 0, 0, 0)')
    draw.stroke_color = color
    for block in blocks:
        top, left, bottom, right = block[-4:]
        if alternatecolors:
            draw.stroke_color = Color('rgba({},{},{}, 1)'.format(
                str(np.random.randint(255)), str(np.random.randint(255)),
                str(np.random.randint(255))))
        draw.rectangle(left=float(left),
                       top=float(top),
                       right=float(right),
                       bottom=float(bottom))
        draw(img)
    return img
Beispiel #25
0
	def generate_track(self) :

		draw = Drawing()
		draw.stroke_width = 2
		draw.stroke_color = Color('red')
		draw.fill_color = Color('transparent')

		points = []

		# Loop over the coordinates to create a list of tuples
		for coords in self.geojson['coordinates'] :
			pt = Point(coords[0], coords[1])
			pt.project(self.rendering_zoom)
			x, y = pt.get_xy()
			x = round(x - (self.minxtile * 256))
			y = round(y - (self.minytile * 256))
			points.append((x, y))

		# draw the polyline
		draw.polyline(points)

		# apply to the image
		draw(self.img)

		# self.rendering_bounds.nw.project(self.rendering_zoom)
		x = int(self.rendering_bounds.nw.tile_x - self.minxtile)
		y = int(self.rendering_bounds.nw.tile_y - self.minytile)

		self.crop(x, y)
		self.img.format = 'jpeg'
		# self.img.save(filename='image.jpg')
		return self.img.make_blob('jpeg')
Beispiel #26
0
 def display_bounding_boxes(self, page_num, bboxes, alternate_colors=True):
     elems = self.elems[page_num]
     page_width, page_height = int(elems.layout.width), int(elems.layout.height)
     img = pdf_to_img(self.pdf_file, page_num, page_width, page_height)
     draw = Drawing()
     draw.fill_color = Color("rgba(0, 0, 0, 0)")
     color = Color("blue")
     draw.stroke_color = color
     for block in bboxes:
         top, left, bottom, right = block[-4:]
         draw.stroke_color = Color(
             "rgba({},{},{}, 1)".format(
                 str(np.random.randint(255)),
                 str(np.random.randint(255)),
                 str(np.random.randint(255)),
             )
         )
         draw.rectangle(
             left=float(left),
             top=float(top),
             right=float(right),
             bottom=float(bottom),
         )
     draw(img)
     return img
Beispiel #27
0
def display_bounding_boxes(img,
                           blocks,
                           alternatecolors=False,
                           color=Color("blue")):
    """
    Displays each of the bounding boxes passed in 'boxes' on an image of the pdf
    pointed to by pdf_file
    boxes is a list of 5-tuples (page, top, left, bottom, right)
    """
    draw = Drawing()
    draw.fill_color = Color("rgba(0, 0, 0, 0)")
    draw.stroke_color = color
    for block in blocks:
        top, left, bottom, right = block[-4:]
        if alternatecolors:
            draw.stroke_color = Color("rgba({},{},{}, 1)".format(
                str(np.random.randint(255)),
                str(np.random.randint(255)),
                str(np.random.randint(255)),
            ))
        draw.rectangle(left=float(left),
                       top=float(top),
                       right=float(right),
                       bottom=float(bottom))
        draw(img)
    display(img)
Beispiel #28
0
 def makeletter(letter, w, h):
     img = Image(width=w, height=h)
     with Drawing() as d:
         d.font = 'Arial'
         d.font_size = 24
         d.gravity = 'center'
         d.text(0, 0, letter)
         d(img)
     return img
Beispiel #29
0
    def compose_image_slide(self, image_path=None, text=None, slide_id=1):

        image_display_size = (300, 190)

        key = '%s-%s-%03d' % (self.emission.uuid, self.content_object.uuid,
                              slide_id)
        path = os.path.join(SLIDE_BASE_DIR, key + '.png')
        url = SLIDE_BASE_URL + key + '.png'

        overlay_image = Image(filename=image_path)

        with Drawing() as draw:

            size = overlay_image.size

            if size[0] > size[1]:
                orientation = 'landscape'
                scale = float(image_display_size[1]) / float(size[1])
            else:
                orientation = 'portrait'
                scale = float(image_display_size[1]) / float(size[0])

            overlay_image.resize(int(size[0] * scale), int(size[1] * scale))

            #size = overlay_image.size

            width = 190
            height = 190
            overlay_image.crop(10, 0, width=width, height=height)

            draw.composite('over',
                           left=int(width / 2) - 20,
                           top=10,
                           width=width,
                           height=height,
                           image=overlay_image)

            # text settings
            draw.font = SLIDE_BASE_FONT
            draw.font_size = 14
            draw.text_interline_spacing = 8
            draw.fill_color = Color('white')
            draw.text_antialias = True

            # draw text
            if text:
                draw.text(220, 10, text)

            # compose image
            with Image(filename=SLIDE_BASE_IMAGE) as image:
                draw(image)
                image.save(filename=path)
                image.save(
                    filename=os.path.join(SLIDE_BASE_DIR, 'debug-%s.png' %
                                          slide_id))

        return url
Beispiel #30
0
    def draw(self):
        image = Image(width=300, height=300, background=Color('black'))

        with Drawing() as draw:
            draw.fill_color = Color(self.props['color'])
            draw.rectangle(left=10, top=10, right=290, bottom=290)
            draw(image)

        return image
Beispiel #31
0
def test_draw_matte():
    white = Color('rgba(0, 255, 255, 5%)')
    transparent = Color('transparent')
    with Image(width=50, height=50, background=white) as img:
        with Drawing() as draw:
            draw.fill_opacity = 0.0
            draw.matte(25, 25, 'floodfill')
            draw.draw(img)
            assert img[25, 25] == transparent
Beispiel #32
0
def test_draw_color():
    white = Color('WHITE')
    black = Color('BLACK')
    with Image(width=50, height=50, background=white) as img:
        with Drawing() as draw:
            draw.fill_color = black
            draw.color(25, 25, 'floodfill')
            draw.draw(img)
            assert img[25, 25] == black
Beispiel #33
0
def test_draw_point():
    white = Color('WHITE')
    black = Color('BLACK')
    with Image(width=5, height=5, background=white) as img:
        with Drawing() as draw:
            draw.stroke_color = black
            draw.point(2, 2)
            draw.draw(img)
            assert img[2, 2] == black
Beispiel #34
0
def test_draw_path_line_user_error():
    with Drawing() as draw:
        # Test missing value
        with raises(TypeError):
            draw.path_line()
        with raises(TypeError):
            draw.path_horizontal_line()
        with raises(TypeError):
            draw.path_vertical_line()
Beispiel #35
0
def test_draw_skew():
    with nested(Color('#fff'), Color('#000')) as (white, black):
        with Image(width=50, height=50, background=white) as img:
            with Drawing() as draw:
                draw.stroke_color = black
                draw.skew(x=11, y=-24)
                draw.line((3, 3), (35, 35))
                draw.draw(img)
                assert img[43, 42] == black
Beispiel #36
0
    def make_frame(self, streams):
        frame = WandImage(width=self.frame_d[0],background=Color('white'), height=self.frame_d[1])   

        for n, stream in enumerate(streams):
            img = WandImage(file=stream)
            x = config.photo_w * ((n >> 1) & 1)
            y = config.photo_h * (n & 1)
            frame.composite(img, left=x+18, top=y+18)
            drawing = WandDrawing()
#            drawing.font = '/home/pi/booth4/fonts/Steelworks.otf'
            drawing.font = '/home/pi/booth6/fonts/Vulturemotor.otf'
            drawing.font_size = 20
#            drawing.font_style = 'italic'
#            drawing.fill_color = Color('orange')
#            drawing.stroke_color = Color('brown')
            drawing.text(310, 660, 'The Mighty Booth') 
            drawing(frame)
        return frame
Beispiel #37
0
def test_draw_translate():
    with nested(Color('#fff'), Color('#000')) as (white, black):
        with Image(width=50, height=50, background=white) as img:
            with Drawing() as draw:
                draw.stroke_color = black
                draw.translate(x=5, y=5)
                draw.line((3, 3), (35, 35))
                draw.draw(img)
                assert img[40, 40] == black
Beispiel #38
0
def create_video_initial_images(content: Content):
    print('> [Video Robot] Creating initial images of the video...')
    VIDEO_PYMAKER_OUTPUT_FILE = os.path.join('content', 'images', 'video-pymaker.png')
    TITLE_INPUT_FILE = os.path.join('content', 'images', 'youtube-thumbnail.png')
    TITLE_OUTPUT_FILE = os.path.join('content', 'images', 'title.png')

    with Image(width=1920, height=1080, background=Color('black')) as video_pymaker_image:
        video_pymaker_image.noise('laplacian', attenuate=1.0)

        with Drawing() as title:
            title.fill_color = Color('white')
            title.font_family = 'Edwardian Script ITC'
            title.font_size = 300
            title.gravity = 'center'
            title.stroke_color = Color('#FFD700')
            title.stroke_width = 1
            title.text_kerning = -1
            video_pymaker_image.annotate('Video Pymaker', title, baseline=-100)

        with Drawing() as complement:
            complement.fill_color = Color('white')
            complement.font_family = 'Edwardian Script ITC'
            complement.font_size = 120
            complement.gravity = 'center'
            complement.stroke_color = Color('#FFD700')
            complement.stroke_width = 0.1
            complement.text_kerning = -1
            video_pymaker_image.annotate('Presents ', complement, baseline=150)

        video_pymaker_image.save(filename=VIDEO_PYMAKER_OUTPUT_FILE)

    with Image(filename=TITLE_INPUT_FILE) as title_image:
        title_image.gaussian_blur(sigma=10)
        title_image.noise('laplacian', attenuate=1.0)

        with Drawing() as title:
            title.fill_color = Color('white')
            title.font_family = 'Edwardian Script ITC'
            title.font_size = 250
            title.gravity = 'center'
            title.text_kerning = -1
            title_image.annotate(f'{content.search_prefix} {content.search_term}', title)

        title_image.save(filename=TITLE_OUTPUT_FILE)
Beispiel #39
0
    def create(self, id, user_id, capture, signature0, signature1, update_at):
        #print("id:",id, user_id, capture, signature0, signature1, update_at)

        import io
        import os
        import datetime
        import modules.QR as QR

        path = setting.BASE_PATH + 'share/' + user_id + '/'

        qr = QR.QR()
        qrImg = qr.create(path)
        outQrData = io.BytesIO()
        qrImg.save(outQrData, format="png")
        #qrImg.show()

        from wand.image import Image
        from wand.drawing import Drawing
        from wand.color import Color

        with Image(filename=setting.MATERIALS_DIR +
                   setting.BASE_IMAGE) as baseImg:

            # Capture
            with Image(file=self.loadImage(capture)) as cap:
                capWidth = 2106
                cap.resize(capWidth, capWidth * cap.height / cap.width)
                baseImg.composite(cap, left=10, top=37)
            # Frame
            with Image(filename=setting.MATERIALS_DIR +
                       setting.FRAME_IMAGE) as frame:
                baseImg.composite(frame, left=7, top=40)

            # QRcode
            with Image(blob=outQrData.getvalue()) as qr:
                qrWidth = 137
                qr.resize(qrWidth, qrWidth)
                baseImg.composite(qr, left=1911, top=1282)

            # Date
            with Drawing() as draw:

                d = datetime.datetime.today()
                dText = '%s.%s.%s' % (d.year, d.month, d.day)
                draw.font = setting.MATERIALS_DIR + setting.FONT_DATA
                draw.fill_color = Color("#FFFFFF")
                draw.font_size = 48
                draw.text_alignment = 'center'
                draw.text(x=1063, y=1470, body=dText)
                draw(baseImg)

            if not os.path.isdir(setting.CERTIFICATE_DIR):
                os.makedirs(setting.CERTIFICATE_DIR)

            baseImg.save(filename=setting.CERTIFICATE_DIR + str(id) + '.png')
        return
Beispiel #40
0
def render_text_line(text, font, size, weight, color=Color('none'), background=None):
    match = re.match("(\w+)(-\w+)?", weight)
    italic = None
    if match:
        weight = match.group(1)
        italic = match.group(2)
    if not italic:
        italic = ""

    #
    # Special case: blank line
    #
    if text == "":
        graphic = new_blank_png(width=5, height=5)
        return (5, 5, graphic)
    
    sequence = lex_line(text, weight)

    images = []
    dummy_image = Image(width=100, height=100, background=None)
    for (level, text) in sequence:
        draw = Drawing()
        draw.font = FONT_INFO[font][level+italic]
        draw.font_size = size
        draw.fill_color = color
        metrics = draw.get_font_metrics(dummy_image, text, False)
        image = new_blank_png(width=int(metrics.text_width), height=int(metrics.y2-metrics.y1))
        draw.text(0, int(metrics.y2), text)
        draw(image)
        images.append((metrics.y2, metrics.y1, image))

    if images == []:
        return None

    max_ascender = max([y2 for (y2,_,_) in images])
    max_descender = -1 * min([y1 for (_,y1,_) in images])
    final_image_width = sum([i.width for (_,_,i) in images])
    final_image_height = int(max_ascender + max_descender)
    final_image = new_blank_png(width=final_image_width, height=final_image_height,
        color=background)

    top_offset = 0
    for (y2,y1,i) in images:
        final_image.composite(i, top_offset, int(max_ascender-y2))
        top_offset = top_offset + i.width

    return (max_ascender, max_descender, final_image)
Beispiel #41
0
# Make certain conversions on the background image.
img.type = 'truecolor'
img.alpha_channel = 'activate'

# Determine the range of binsource lines we need to use.  We're guaranteed
# they're all in the binsource lines[] array.
if bankNumber < 4:
	bankNumber = bankNumber ^ 2
startIndex = bankNumber * 4 * 8 * 4 + pageInBank * 4 * 8
endIndex = startIndex + 4 * 8

# Loop on lines on the selected page.  We're going to assume that the boxes are
# in 1-to-1 correspondence with the binsource digit, in the order read from 
# disk, except that there may be less boxes (on the last page of a bank).
draw = Drawing()
row = 0
lastRight = 1000000
boxIndex = 0
for index in range(startIndex, endIndex):
	if boxIndex >= len(boxes):
		print 'Out of boxes on page'
		break
	# Loop on the octal digits in the row.
	col = 0
	characterIndex = 0
	characters = list(lines[index])
	for octalDigitIndex in range(0, 8 * 6):
		if boxIndex >= len(boxes):
			print 'Out of boxes in row'
			break
Beispiel #42
0
import argparse
import sys
import yaml
import re

from wand.image import Image
from wand.color import Color
from wand.drawing import Drawing
from wand.display import display

image_width = 400
image_height = 60

image = Image(width=image_width, height=image_height, background=Color('white'))

draw = Drawing()
draw.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOTF/TTF/Lato-Reg.ttf'
draw.font_size = 36
draw.fill_color = Color('black')
metrics = draw.get_font_metrics(image, "losing photos", False)

pos_col = int((image_width - metrics.text_width)/2)
pos_row = int(metrics.ascender + (image_height - metrics.text_height)/2) 

print "DEBUG ", pos_col, pos_row

draw.text(pos_col, pos_row, "losing photos")
draw(image)

image.save(filename="_00.png")
Beispiel #43
0
def layer05():
    req_width = 240
    req_height = 240
    contents_panel_text = new_blank_png(req_width, req_height)

    draw = Drawing()

    draw.font = FONT_BOLD
    draw.font_size = 18
    draw.fill_color = Color('black')
    draw.text(20, 45, "In this issue:")

    draw.font = FONT_ITALIC
    draw.font_size = 18
    draw.fill_color = Color('black')

    line_spacing = int(float(draw.font_size) * 1.22)
    (line_x, line_y) = (20, 81)
    lines = ["How to keep", "your toddler safe from",
        "unwanted event horizons",
        " ",
        "Best five telescopes", "for kids under six"]
    for l in lines:
        draw.text(line_x, line_y, l)
        line_y = line_y + line_spacing 

    draw(contents_panel_text)
    return contents_panel_text
Beispiel #44
0
def layer02():
    draw = Drawing()
    draw.font = FONT_REGULAR
    draw.font_size = 144
    draw.fill_color = Color('rgb(216,224,34)')
    draw.text(0, 120, "21")

    draw.font = FONT_BLACK
    draw.text(170, 120, "CA")

    draw.font = FONT_BOLD
    draw.font_size = 18
    draw.text(480, 30, "2014/01")
   
    draw.font = FONT_REGULAR
    draw.font_size = 36
    draw.fill_color = Color('white')
    draw.text(0, 160, "twenty-first century astronomer")
 
    req_width = 570
    req_height = 170
    masthead_image = new_blank_png(req_width, req_height)
    draw(masthead_image)

#    opacity_mask = new_blank_png(570, 170, Color('rgb(200,200,200'))
#    masthead_image.composite_channel(channel='alpha', image=opacity_mask, operator='copy_opacity')

    return masthead_image
Beispiel #45
0
	for i in range(0, 8):
		replaceColorsInImage(images[i], Color(matchColor), Color(scanColor))
	replaceColorsInImage(img, Color(scanColor), Color(matchColor))

# Make certain conversions on the background image.
img.type = 'truecolor'
img.alpha_channel = 'activate'

# Determine the range of binsource lines we need to use.  We're guaranteed
# they're all in the binsource lines[] array.
if bankNumber < 4:
	bankNumber = bankNumber ^ 2
startIndex = bankNumber * 4 * 8 * 4 + pageInBank * 4 * 8
endIndex = startIndex + 4 * 8

draw = Drawing()
evilColor = Color("#FF00FF")
extraColor = Color("#FF8000")
draw.stroke_color = evilColor
draw.stroke_width = 4
draw.fill_opacity = 0

# Draw empty frames around all of the rejected boxes.
for i in range(0,len(rejectedBoxes)):
	boxFields = rejectedBoxes[i].split()
	boxLeft = int(boxFields[1])
	boxBottom = backgroundHeight - 1 - int(boxFields[2])
	boxRight = int(boxFields[3])
	boxTop = backgroundHeight - 1 - int(boxFields[4])
	draw.line((boxLeft,boxTop), (boxRight,boxTop))
	draw.line((boxLeft,boxBottom), (boxRight,boxBottom))
Beispiel #46
0
import argparse
import sys
import yaml
import re

from wand.image import Image
from wand.color import Color
from wand.drawing import Drawing
from wand.display import display

#full_text = ["The first line", "and a second line", "... finally a third line."]
full_text = ["The first line"]
FONT_SIZE = 48

dummy_image = Image(width=100, height=100, background=Color('black'))
draw = Drawing()
draw.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOFL/TTF/Lato-Reg.ttf'
draw.font_size = FONT_SIZE
draw.fill_color = Color('black')


rendered_segments = []
for text in full_text:
    metrics = draw.get_font_metrics(dummy_image, text, False)
    yMax = int(metrics.y2)
    yMin = -1 * int(metrics.y1)
    segment_width = int(metrics.text_width)
    draw = Drawing()
    draw.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOFL/TTF/Lato-Reg.ttf'
    draw.font_size = FONT_SIZE
    draw.fill_color = Color('black')
Beispiel #47
0
def slice02():
    # Resize image to height (but do not change the aspect ratio)
    #
    req_width = 595
    req_height = 486
    baby_img = Image(filename=IMAGE_PATH + "baby_cc_sh.png")
    baby_img = resize_to_height(baby_img, req_height)

    # For this particular image, reflect image along vertical
    # axis to have face directed towards right of page.
    #
    baby_img.flop()

    # Create the the gradient transition that will later be used
    # in the opacity mask.
    #
    gradient_blob = create_gradient_blob(req_height, 75, gradient([
        (1.0, (0x00, 0x00, 0x00), (0xFF, 0xFF, 0xFF)), # top
    ]))
    gradient_img = Image(blob=gradient_blob)
    gradient_img.rotate(90.0)

    # When building the opacity mask, must start with an image
    # having a solid colour (i.e., begin as a "matte" image).
    # Without this, the later "composite_channel" operations
    # will simply not work.
    #
    opacity_mask = new_blank_png(req_width, req_height, color=Color('white'))
    left_field = new_blank_png(230, req_height, Color('white'))
    right_field = new_blank_png(290, req_height, Color('black'))
    opacity_mask.composite(left_field, 0, 0)
    opacity_mask.composite(right_field, 230+75, 0)
    opacity_mask.composite(gradient_img, 230, 0)

    # Now take the resized baby image and have it fade to the right
    # (in order to blend with later operations).
    #
    face_img = new_blank_png(req_width, req_height)
    face_img.composite(baby_img, 0, 0)
    face_img.composite_channel(channel='all_channels', image=opacity_mask, 
        operator='copy_opacity')

    # Bring in the illustrative image that will eventually be blended in
    # with the child's face.
    #
    accent_img = Image(filename = IMAGE_PATH + "funky_illustration.png")
    accent_img = resize_to_percent(accent_img, 60)
    accent_img = resize_to_height(accent_img, 486)

    cropped_img = accent_img.clone()
    cropped_img.crop(top=0, left=275, width=340, height=486)
    screen_img = new_blank_png(340, 486, color=Color('rgb(150,150,150)'))
    cropped_img.composite_channel(channel='all_channels', image=screen_img, 
        operator='screen')

    accent_img = new_blank_png(req_width, req_height)
    accent_img.composite_channel(channel='all_channels', image=cropped_img, 
        operator='over', left=255, top=0)
    accent_img.gaussian_blur(3.0, 1.0)

    opacity_mask = new_blank_png(req_width, req_height, color=Color('white'))
    left_field = new_blank_png(260, req_height, Color('black'))
    right_field = new_blank_png(290, req_height, Color('white'))
    opacity_mask.composite(left_field, 0, 0)
    opacity_mask.composite(right_field, 260+75, 0)
    gradient_img.rotate(180)
    opacity_mask.composite(gradient_img, 260, 0)
    accent_img.composite_channel(channel='all_channels', image=opacity_mask, 
        operator='copy_opacity')

    # Now layer the accent image with the child's face
    #
    accent_img.composite_channel(channel='all_channels', image=face_img,
        operator='over')
    full_slice = accent_img 

    # Finally, add the text field on the right of the image.
    #
    text_field = new_blank_png(212, req_height, color=Color('rgb(190,30,45)'))
    text_field_mask = new_blank_png(212, req_height, color=Color('rgb(220,220,220)'))
    text_field.composite_channel(channel='all_channels', image=text_field_mask, 
        operator='copy_opacity')
    full_slice.composite(text_field, 384, 0)

    draw = Drawing()
    draw.font = FONT_BOLD
    draw.font_size = 24
    draw.fill_color = Color('white')
    draw.text(395, 175, "Liam Mulcahy")
    draw.font = FONT_REGULAR
    draw.font_size = 20
    draw.text(395, 200, "Eyes to the Future")
    draw.font = FONT_ITALIC
    draw.font_size = 20
    draw.text(395, 250, 'How dreams of')
    draw.text(395, 275, 'future enterprise')
    draw.text(395, 300, 'success are')
    draw.text(395, 325, 'starting while still')
    draw.text(395, 350, 'in nappies!')
    draw(full_slice)
   
    # Done.
    # 
    return full_slice
def generate(count):
    # ---------------get three colors-------------------------------
    colorString = random.choice(result)
    color = []
    for i in colorString:
        color += [int(i)]
    # for i in range(len(color)):
    #     color[i] = math.floor(color[i]/255*65535)
    color1 = color[0:3]
    color2 = color[3:6]
    color3 = color[6:9]
    # --------------------------------------------------------------

    # ----------get the base layer texture--------------------------
    Scenes = pathwalk('./SceneData')

    randomScene = random.choice(Scenes)
    randomScene = randomScene[0] + '/' + randomScene[1]
    print(randomScene)
    randomSceneImage = Image(filename=randomScene)

    widthRange = randomSceneImage.size[0] - 100
    heightRange = randomSceneImage.size[1] - 32

    randomSceneImage.crop(left=random.randint(0, widthRange), top=random.randint(0, heightRange), width=100, height=32)
    # randomSceneImage.save(filename='.\\photoWand\\'+str(j+1) + '_texture.jpg')
    # --------------------------------------------------------------

    # ----------create the base layer, base texture +base color-----

    baseImage = Image(width=100, height=32, background=Color('rgb('+str(color1[0])+','+str(color1[1])+','+str(color1[2])+')'))

    # print('base_color = ' + 'rgb('+str(color1[0])+','+str(color1[1])+','+str(color1[2])+')')
    baseImage.composite_channel(channel='undefined', image=randomSceneImage, operator='blend', left=0, top=0)
    baseImage.gaussian_blur(4, 10)
    baseImage.resolution = (96, 96)
    # --------------------------------------------------------------

    # -----generate font--------------------------------------------
    word = randomWords()
    fonts = pathwalk('./fonts/font_en/')
    randomFont = random.choice(fonts)
    randomFont = randomFont[0] + randomFont[1]

    initialPointsize = 45

    draw = Drawing()
    draw.font = randomFont

    tmp = int(math.floor(abs(random.gauss(0, 1))*6))
    if random.randint(1, 2) == 1:
        rotateX = random.randint(0, tmp)
    else:
        rotateX = random.randint(360-tmp, 360)

    draw.rotate(rotateX)
    # --------------------------------------------------------------
    # --------get suitable FontPointSize----------------------------
    draw.font_size = initialPointsize
    metric = draw.get_font_metrics(image=baseImage, text=word)

    while metric.text_width > 100 or metric.text_height > 36:
        initialPointsize -= 5
        draw.font_size = initialPointsize
        metric = draw.get_font_metrics(image=baseImage, text=word)
    # --------------------------------------------------------------

    # ----------italic----------------------------------------------
    if random.random() > 0.5:
        draw.font_style = 'italic'
    # --------------------------------------------------------------

    # ----------underline-------------------------------------------
    if random.random() > 0.5:
        draw.text_decoration = 'underline'
    # --------------------------------------------------------------

    # ----------gravity---------------------------------------------
    draw.gravity = 'center'
    # --------------------------------------------------------------

    # --------------shadow/border-----------------------------------
    if random.random() < 0.5:
        # shadow
        addx = math.ceil(random.gauss(0, 2))
        addy = math.ceil(random.gauss(0, 2))
        draw.fill_color = Color('black')
        draw.text(x=abs(int(addx)), y=abs(int(addy)), body=word)

    else:
        # border
        draw.stroke_color = Color('rgb('+str(color3[0])+','+str(color3[1])+','+str(color3[2])+')')
        draw.stroke_width = math.ceil(initialPointsize/10)-1
    # --------------------------------------------------------------

    # ----------print word------------------------------------------
    draw.fill_color = Color('rgb('+str(color2[0])+','+str(color2[1])+','+str(color2[2])+')')
    draw.text(x=0, y=0, body=word)
    draw.draw(baseImage)
    # --------------------------------------------------------------

    # ------------gray----------------------------------------------
    baseImage.colorspace = 'gray'
    # --------------------------------------------------------------

    print(word)
    baseImage.save(filename='./photo_en/'+str(count+1)+'_'+word+'.jpg')
for ascii in range(128):
	filename = "asciiFont/match" + str(ascii) + ".png"
	if os.path.isfile(filename):
		imagesMatch.append(Image(filename=filename))
	else:
		imagesMatch.append(Image(filename="asciiFont/match127.png"))
imagesNomatch = []
for ascii in range(128):
	filename = "asciiFont/nomatch" + str(ascii) + ".png"
	if os.path.isfile(filename):
		imagesNomatch.append(Image(filename=filename))
	else:
		imagesNomatch.append(Image(filename="asciiFont/nomatch127.png"))

# Prepare a drawing-context.
draw = Drawing()
evilColor = Color("#FF00FF")
extraColor = Color("#FF8000")
draw.stroke_color = evilColor
draw.stroke_width = 4 * scale
draw.fill_opacity = 0

# Draw empty frames around all of the rejected boxes.
for i in range(0,len(rejectedBoxes)):
	boxTop = rejectedBoxes[i]['boxTop']
	boxBottom= rejectedBoxes[i]['boxBottom']
	boxLeft = rejectedBoxes[i]['boxLeft']
	boxRight = rejectedBoxes[i]['boxRight']
	draw.line((boxLeft,boxTop), (boxRight,boxTop))
	draw.line((boxLeft,boxBottom), (boxRight,boxBottom))
	draw.line((boxRight,boxTop), (boxRight,boxBottom))
Beispiel #50
0
    # print('base_color = ' + 'rgb('+str(color1[0])+','+str(color1[1])+','+str(color1[2])+')')
    baseImage.composite_channel(channel='undefined', image=randomSceneImage, operator='blend', left=0, top=0)
    baseImage.gaussian_blur(4, 10)
    baseImage.resolution = (96, 96)
    # --------------------------------------------------------------

    # -----generate font--------------------------------------------
    word = python2access.randomWords()
    fonts = pathwalk('.\\googleFonts\\')
    randomFont = random.choice(fonts)
    randomFont = randomFont[0] + randomFont[1]

    initialPointsize = 45

    draw = Drawing()
    draw.font = randomFont

    tmp = int(math.floor(abs(random.gauss(0, 1))*6))
    if random.randint(1, 2) == 1:
        rotateX = random.randint(0, tmp)
    else:
        rotateX = random.randint(360-tmp, 360)

    draw.rotate(rotateX)
    # --------------------------------------------------------------
    # --------get suitable FontPointSize----------------------------
    draw.font_size = initialPointsize
    metric = draw.get_font_metrics(image=baseImage, text=word)

    while metric.text_width > 100 or metric.text_height > 36:
Beispiel #51
0
def slice03():
    full_slice = new_blank_png(595, 182)

    # Two solid-colour areas, one on left and one on right
    #
    left_field = new_blank_png(299, 182, color=Color('rgb(44,128,64)'))
    right_field = new_blank_png(297, 182, color=Color('rgb(127,184,141)'))
    full_slice.composite(left_field, 0, 0)
    full_slice.composite(right_field, 299, 0)
   
    draw = Drawing()

    # Text on the left field
    #
    draw.font = FONT_BOLD
    draw.font_size = 18
    draw.fill_color = Color('white')
    draw.text(30, 85, "Smartphone Babyproofing")

    # Unfortunately don't yet have strokewidth
    #
    draw.line((29,95), (298,95))
    draw.line((29,96), (298,96))
    draw.line((29,97), (298,97))

    draw.font = FONT_REGULAR
    draw.font_size = 18
    draw.text(30, 125, "Tips on how to use those")
    draw.text(30, 147, "safety features you")
    draw.text(30, 169, "always forget to enable...")

    # Text on the right field
    #
    draw.font = FONT_BOLD
    draw.font_size = 18
    draw.fill_color = Color('black')
    draw.text(328, 85, "School savings")

    # Yada yada yada ...
    #
    draw.line((328,95), (595,95))
    draw.line((328,96), (595,96))
    draw.line((328,97), (595,97))

    draw.font = FONT_REGULAR
    draw.font_size = 18
    draw.text(328, 125, "Successful $$$ strategies")  ## Still have euro-symbol issues
    draw.text(328, 147, "for getting junior into the")
    draw.text(328, 169, "best business school")

    # ... and now drawing the text 
    #
    draw(full_slice)

    # Add the accent images on top
    #
    graphics_slice = new_blank_png(595, 182)
    
    left_image = Image(filename = IMAGE_PATH + "smartphone.png")
    left_image = resize_to_width(left_image, 299)

    right_image = Image(filename = IMAGE_PATH + "building.png")
    right_image = resize_to_width(right_image, 298)

    graphics_slice.composite(left_image, 0, 0)
    graphics_slice.composite(right_image, 299, 0)
    opacity_mask = new_blank_png(595, left_image.height, color=Color('rgb(75,75,75)'))
    graphics_slice.composite_channel(channel='all_channels', image=opacity_mask, 
        operator='copy_opacity')

    full_slice.composite_channel(channel='all_channels', image=graphics_slice, 
        operator='over', top=0, left=0)
 
    # Done.
    #
    return full_slice
Beispiel #52
0
def slice01():
    req_width = 595
    req_height = 139
    masthead_image = new_blank_png(req_width, req_height, Color('white'))

    # Cannot yet draw a rectangle. Therefore to get the collection of boxes
    # and their colours, we create images that are then composited.
    box1 = new_blank_png(384, 139, Color('rgb(192,30,45)'))
    box2 = new_blank_png(173, 139, Color('rgb(224,137,145)'))
    masthead_image.composite(box1, 0, 0)
    masthead_image.composite(box2, 384, 0)
    
    draw = Drawing()
    draw.font = FONT_BOLD
    draw.font_size = 72
    draw.fill_color = Color('white')
    draw.text(169, 82, "entre")
    draw.text(60, 124, "preneur")
    
    draw.font = "../fonts/arvo/Arvo-Regular.ttf"
    draw.font_size = 115
    draw.fill_color = Color('black')
    draw.text(390, 125, "2.0")
    
    draw(masthead_image)

    # Cannot yet rotate the text in the same step as the drawing,
    # so draw rectangle with text and then rotate it.
    #
    box3 = new_blank_png(139, 39, Color('rgb(192,30,45)'))
    draw = Drawing()
    draw.font = "../fonts/arvo/Arvo-Regular.ttf"
    draw.font_size = 17
    draw.fill_color = Color('white')
    draw.text(5, 25, "November 2013")
    draw(box3)
    box3.rotate(-90)
    masthead_image.composite(box3, 557, 0)

    return masthead_image
    if n>=interval*intervalStep:
        print "%s, %s%% > %i tiles so far, %i to go, %s merged, %s copied" % \
            (helper.timeString(int(time.time()-start_time)), str(int(round(n/srcTotal*100.00))), \
             n, srcTotal-n, mergedTiles, copiedTiles)
        interval+=1
    
    if i in targetFiles:
        # Backup image
        if keepOriginals=="true":
            shutil.copy(target+"/"+i, target+"/"+i+".orig")
        else:
            pass
        # Merge images with Wand / ImageMagick
        sourceImg = Image(filename=src+"/"+i)
        targetImg = Image(filename=target+"/"+i)
        draw = Drawing()
        draw.composite(image=sourceImg, operator='src_over', left=0, top=0, \
                       width=sourceImg.width, height=sourceImg.height)
        draw.draw(targetImg)
        targetImg.save(filename=target+"/"+i)
        mergedTiles = mergedTiles+1
    else:
        # Recreate path if needed
        try:
            os.makedirs(target+"/".join(i.split("/")[:-1]))
        except:
            pass
        shutil.copy(src+"/"+i, target+"/"+i)
        copiedTiles = copiedTiles+1

    n+=1
Beispiel #54
0
import re

from wand.image import Image
from wand.color import Color
from wand.drawing import Drawing
from wand.display import display

weight_sequence = ['ultralight', 'light',
    'regular', 'bold', 'black']

image_width = 400
image_height = 60

dummy_image = Image(width=image_width, height=image_height, background=Color('white'))

draw = Drawing()
draw.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOFL/TTF/Lato-Reg.ttf'
draw.font_size = 36
draw.fill_color = Color('black')
metrics_01 = draw.get_font_metrics(dummy_image, "21", False)

draw.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOFL/TTF/Lato-Bla.ttf'
draw.font_size = 36
draw.fill_color = Color('black')
metrics_02 = draw.get_font_metrics(dummy_image, "CV", False)

image_01 = Image(width=int(metrics_01.text_width),
    height=int(metrics_01.text_height), background=None)
draw_01 = Drawing()
draw_01.font = '/Users/zastre/Dev/fimsi/sandbox/fonts/LatoOFL/TTF/Lato-Reg.ttf'
draw_01.font_size = 36
Beispiel #55
0
#!/usr/bin/python

from wand.image import Image
from wand.color import Color
from wand.drawing import Drawing

# Create a blank image
image_width = 300
image_height = 400
img = Image(width=image_width, height=image_height, background=Color('rgb(44,128,64)'))

# Need a drawing object for rendering.
# Here there are some canvas (?) settings being established
d = Drawing()
d.fill_color = Color('rgb(255,255,255)')
d.font = 'Arvo-Regular.ttf'
d.font_size = 48

# Want some info on how big the text will be
# when drawn, then use it for calculations
#
fm = d.get_font_metrics(img, 'Hello!')
height = fm.text_height
width = fm.text_width
pos_x = int((image_width - width) / 2)
pos_y = int((image_height) / 2)

# Specify the coordinate of the lower-left
# position of the text (where 0,0 is the
# upper-left hand corner o the canvas).
#
Beispiel #56
0
         (0x70,0xA4,0xB2),
         (0x6F,0x3D,0x86),
         (0x58,0x8D,0x43),
         (0x35,0x28,0x79),
         (0xB8,0xC7,0x6F),
         (0x6F,0x4F,0x25),
         (0x43,0x39,0x00),
         (0x9A,0x67,0x59),
         (0x44,0x44,0x44),
         (0x6C,0x6C,0x6C),
         (0x9A,0xD2,0x84),
         (0x6C,0x5E,0xB5),
         (0x95,0x95,0x95)]

img = Image(width=160, height=200, resolution=300)
drw = Drawing()
drw.stroke_width = 0
bgcolor = 0 

"""
(WxH)
Mc_data is a stream that describes a 40x25 cell multi color bitmap, as a matrix.
Each cell is 4x8 px.
The full stream is 8000 bytes long.
Mc_data has each cell as its lines in order.
Two contiguous cells:
00 01 02 03 | 32 33 34 35 |
04 05 06 07 | 36 37 38 39 |
...
28 29 30 31 | 60 61 62 63 |
Beispiel #57
0
def main():
	args = get_args()

	draw = Drawing()
	draw.font = args.font_file
	draw.font_size = args.font_size

	font_name = args.font_name
	out_dir = args.out_dir

	img_ref = Image(width=1000, height=1000)

	if args.verbose:
		print "Writing " + out_dir + "/" + font_name + ".c"
	f = open(out_dir + "/" + font_name + ".c", 'wb+')
	write_comment(f)
	f.write("#include \"font.h\"\n\n")

	font_height = 0
	range_first = 0x20
	range_last = 0x7d
	font_width = []
	max_width = 0
	for x in range(range_first, range_last + 1):
		letter = chr(x)
		metrics = draw.get_font_metrics(img_ref, letter)
		text_height = int(round(metrics.text_height + 2))
		if font_height == 0:
			font_height = text_height
		assert (font_height == text_height), "font height changed!"
		if max_width == 0:
			max_width = metrics.maximum_horizontal_advance + 2
		assert (max_width == metrics.maximum_horizontal_advance + 2), \
			"font advance width changed!"
		text_width = int(round(metrics.text_width + 2))
		font_width.append(text_width)
		img = Image(width=text_width, height=text_height)
		d = draw.clone()
		d.text(0, int(metrics.ascender), letter)
		d(img)

		img.depth = 1;

		f.write("static const unsigned char ")
		f.write("letter_" + str(hex(x)[2:]) + "[] = {\n")
		c_hex_print(f, img.make_blob(format='A'))
		f.write("};\n\n")
		img.close()

	f.write("static const struct font_letter letters[] = {\n")
	for x in range(range_first, range_last + 1):
		letter_var_name = "letter_" + str(hex(x)[2:])
		f.write("\t{ " + letter_var_name + ", ")
		f.write("sizeof(" + letter_var_name + "), ")
		f.write(str(font_width[x - range_first]) + "},\n")
	f.write("};\n\n")

	f.write("const struct font font_" + font_name + " = {\n")
	f.write("\t.first = " + str(hex(range_first)) + ",\n")
	f.write("\t.last = " + str(hex(range_last)) + ",\n")
	f.write("\t.letters = letters,\n")
	f.write("\t.height = " + str(font_height) + ",\n")
	f.write("\t.max_width = " + str(max_width) + ",\n")
	f.write("};\n")
	f.close()

	if args.verbose:
		print "Writing " + out_dir + "/" + font_name + ".h"
	f = open(out_dir + "/" + font_name + ".h", 'wb+')
	write_comment(f)
	f.write("#ifndef __" + font_name.upper() + "_H\n");
	f.write("#define __" + font_name.upper() + "_H\n");
	f.write("#include \"font.h\"\n")
	f.write("extern const struct font font_" + font_name + ";\n")
	f.write("#endif /*__" + font_name.upper() + "_H*/\n");
	f.close()
Beispiel #58
0
		shottime = int(NightSettings['ShotInterval'])

	if (int((dt.datetime.now() - last_run).total_seconds()) > shottime):
		if F.IsDayLight(Settings['Latitude'],Settings['Longitude'],Settings['Elevation']):
#			syslog.syslog(syslog.LOG_INFO, 'Setting Day Parameters')
			F.SetCamera(cam,DaySettings)
		else:
#			syslog.syslog(syslog.LOG_INFO, 'Setting Night Parameters')
			F.SetCamera(cam,NightSettings)
#		syslog.syslog(syslog.LOG_INFO, 'Taking Photo')
		cam.capture(Settings['FTPFile'])

		img = Image(filename=Settings['FTPFile'])
		OverImg = Image(filename='/boot/TMLogo.png')

		draw = Drawing()
		draw.composite(operator='over',left=img.width - OverImg.width - 5,top=5,width=OverImg.width,height=OverImg.height,image=OverImg)
		draw(img)

                draw = Drawing()
                draw.fill_color = Color('blue')
		draw.fill_opacity = 0.5
		draw.rectangle(0,img.height - 30,img.width,img.height)
                draw(img)

		draw = Drawing()
		draw.font = 'wandtests/assets/League_Gothic.otf'
		draw.font_size = 20
		draw.fill_color = Color('white')
		draw.text_alignment = 'left'
		draw.text(5, img.height - 5, Settings['Description'])