Exemple #1
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
Exemple #2
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
Exemple #3
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)
Exemple #4
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
Exemple #5
0
async def remix_meeme(upper_text, lower_text, picture_name, endname):
    main_image = remiximage(filename=picture_name)
    main_image.resize(
        1024,
        int(((main_image.height * 1.0) / (main_image.width * 1.0)) * 1024.0))
    upper_text = "\n".join(wrap(upper_text,
                                get_warp_length(main_image.width))).upper()
    lower_text = "\n".join(wrap(lower_text,
                                get_warp_length(main_image.width))).upper()
    lower_margin = MARGINS[lower_text.count("\n")]
    text_draw = Drawing()
    text_draw.font = join(getcwd(),
                          "userbot/utils/styles/MutantAcademyStyle.ttf")
    text_draw.font_size = 100
    text_draw.text_alignment = "center"
    text_draw.stroke_color = Color("black")
    text_draw.stroke_width = 3
    text_draw.fill_color = Color("white")
    if upper_text:
        text_draw.text((main_image.width) // 2, 80, upper_text)
    if lower_text:
        text_draw.text((main_image.width) // 2,
                       main_image.height - lower_margin, lower_text)
    text_draw(main_image)
    main_image.save(filename=endname)
Exemple #6
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
Exemple #7
0
    def draw_strip(self, filename):
        led_width = 20
        led_height = 20
        color_width = int(led_width * 0.8)
        color_height = int(led_height * 0.8)

        img = Image(width=(led_width * self.led_count),
                    height=led_height,
                    background=Color('#000000'))

        draw = Drawing()
        draw.stroke_width = 3

        for n in range(0, self.led_count):
            draw.fill_color = Color('#%02x%02x%02x' %
                                    (self.led_list[n][0], self.led_list[n][1],
                                     self.led_list[n][2]))
            draw.rectangle(left=int(led_width * n + 0.5 *
                                    (led_width - color_width)),
                           top=int(0.5 * (led_height - color_height)),
                           width=color_width,
                           height=color_height)
        draw(img)

        img.save(filename=filename)
def saveFile() :
    global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR, outImageG, outImageB, inW, inH, outW, outH
    draw = Drawing() # 빈 판을 준비

    saveFp = asksaveasfile(parent=window, mode='w', defaultextension='.png'
      ,filetypes = (("그림파일", "*.gif;*.jpg;*.png;*.tif;*.bmp"), ("모든파일", "*.*")))

    # 빈 판에 칼라찍기. '#000000~#FFFFFF'
    for  i  in range(outH) :
        for k in range(outW) :
            dataR = outImageR[i][k];dataG = outImageG[i][k];dataB = outImageB[i][k];
            hexStr = '#'
            if dataR > 15 :
                hexStr += hex(dataR)[2:]
            else :
                hexStr += ( '0' + hex(dataR)[2:] )
            if dataG > 15 :
                hexStr += hex(dataG)[2:]
            else :
                hexStr += ( '0' + hex(dataG)[2:] )
            if dataB > 15 :
                hexStr += hex(dataB)[2:]
            else :
                hexStr += ( '0' + hex(dataB)[2:] )
            draw.fill_color = Color(hexStr)
            draw.color(k, i, 'replace')

    with Image(filename=filename) as img :
        draw(img)
        img.save(filename=saveFp.name)

    print('Save... OK!')
Exemple #9
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)
 def draw_text(self,
               image,
               x,
               y,
               text,
               font_size=15,
               font_style='normal',
               font=None,
               text_alignment='left',
               text_color='Black',
               filename=None,
               is_display=False):
     draw = Drawing()
     print('draw text={} in x={}, y={}'.format(text, x, y))
     if font is not None:
         draw.font = font
     draw.fill_color = Color(text_color)
     draw.font_size = font_size
     draw.font_style = font_style
     draw.text_alignment = text_alignment
     draw.text(x, y, text)
     draw(image)
     if is_display:
         display(image)
     if filename is not None:
         image.save(filename=filename)
     return image
Exemple #11
0
def generate_meme(upper_text, lower_text, picture_name_orig,
                  picture_name_target):
    main_image = Image(filename=join(TEMPLATES_FOLDER, picture_name_orig))
    main_image.resize(
        1024,
        int(((main_image.height * 1.0) / (main_image.width * 1.0)) * 1024.0))

    upper_text = "\n".join(wrap(upper_text,
                                get_warp_length(main_image.width))).upper()
    lower_text = "\n".join(wrap(lower_text,
                                get_warp_length(main_image.width))).upper()
    lower_margin = MARGINS[lower_text.count("\n")]

    text_draw = Drawing()

    text_draw.font = join(getcwd(), "impact.ttf")
    text_draw.font_size = 70
    text_draw.text_alignment = "center"
    text_draw.stroke_color = Color("black")
    text_draw.stroke_width = 3
    text_draw.fill_color = Color("white")

    if upper_text:
        text_draw.text(int(main_image.width / 2), 80, upper_text)
    if lower_text:
        text_draw.text(int(main_image.width / 2),
                       main_image.height - lower_margin, lower_text)

    text_draw(main_image)

    main_image.save(filename=join(getcwd(), MEME_FOLDER, picture_name_target))
Exemple #12
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')
Exemple #13
0
def saveFile():
    global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH
    draw = Drawing()  # 빈 판
    # 빈 판에 컬러 -> #000000 ~ #FFFFFF
    saveFp = asksaveasfile(parent=window,
                           mode='w',
                           defaultextension='.png',
                           filetypes=(("그림파일",
                                       "*.gif;*.jpg;*.png;*.tif;*.bmp"),
                                      ("모든파일", "*.*")))
    for i in range(outW):
        for j in range(outH):
            dataR = outImage[i][j][0]
            dataG = outImage[i][j][1]
            dataB = outImage[i][j][2]
            hexStr = '#'
            if dataR > 15:
                hexStr += hex(dataR)[2:]
            else:
                hexStr += ('0' + hex(dataR)[2:])
            if dataG > 15:
                hexStr += hex(dataG)[2:]
            else:
                hexStr += ('0' + hex(dataG)[2:])
            if dataB > 15:
                hexStr += hex(dataB)[2:]
            else:
                hexStr += ('0' + hex(dataB)[2:])
            draw.fill_color = Color(hexStr)
            draw.color(j, i, 'replace')
    with Image(filename=filename) as img:
        draw(img)
        img.save(filename=saveFp.name)
    print("SAVE OK")
Exemple #14
0
 def display_boxes(self, pdf_file, boxes, alternate_colors=False):
     """
     Displays each of the bounding boxes passed in 'boxes' on images of the pdf
     pointed to by pdf_file
     boxes is a list of 5-tuples (page, top, left, bottom, right)
     """
     imgs = []
     colors = [Color('blue'), Color('red')]
     boxes_per_page = defaultdict(int)
     boxes_by_page = defaultdict(list)
     for i, (page, top, left, bottom, right) in enumerate(boxes):
         boxes_per_page[page] += 1
         boxes_by_page[page].append((top, left, bottom, right))
     for i, page_num in enumerate(boxes_per_page.keys()):
         img = pdf_to_img(pdf_file, page_num)
         draw = Drawing()
         draw.fill_color = Color('rgba(0, 0, 0, 0.0)')
         for j, (top, left, bottom,
                 right) in enumerate(boxes_by_page[page_num]):
             draw.stroke_color = colors[
                 j % 2] if alternate_colors else colors[0]
             draw.rectangle(left=left, top=top, right=right, bottom=bottom)
         draw(img)
         imgs.append(img)
     return imgs
Exemple #15
0
 def _caption_sanandreas(self):
     caption = self.text
     drawing = Drawing()
     drawing.font = 'assets/fonts/TwCenMTStd-ExtraBold.otf'
     drawing.font_size = self.width / 20
     drawing.text_interline_spacing = drawing.font_size / 5
     drawing.fill_opacity = 0.8
     drawing.gravity = 'south'
     text = fill(caption, 30)
     drawing.fill_color = Color('#000')
     offset = drawing.font_size / 12
     drawing.translate(offset, self.height / 15)
     drawing.text(0, 0, text)
     drawing.translate(-offset, offset)
     drawing.fill_color = Color('#eee')
     drawing.text(0, 0, text)
     return caption, drawing
Exemple #16
0
 def _caption_seinfeld(self):
     caption = self.text
     drawing = Drawing()
     drawing.font = 'assets/fonts/NimbusSanL-RegIta.otf'
     drawing.font_size = self.width / 14
     text = fill(caption, 25)
     drawing.fill_color = Color('#000')
     drawing.translate(10, self.height / 12)
     # the number of shadows depends on image width, with a min of 1
     shadows = max(int(self.width / 150), 1)
     for _ in range(shadows):
         drawing.translate(-1, 1)
         drawing.gravity = 'south'
         drawing.text(0, 0, text)
     drawing.fill_color = Color('#fff')
     drawing.text(0, 0, text)
     return caption, drawing
 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)
Exemple #18
0
 def display_boxes(self,
                   tree,
                   html_path,
                   filename_prefix,
                   alternate_colors=False):
     """
     Displays each of the bounding boxes passed in 'boxes' on images of the pdf
     pointed to by pdf_file
     boxes is a list of 5-tuples (page, top, left, bottom, right)
     """
     imgs = []
     colors = {
         "section_header": Color('blue'),
         "figure": Color('green'),
         "figure_caption": Color('green'),
         "table_caption": Color('red'),
         "list": Color('yellow'),
         "paragraph": Color('gray'),
         "table": Color('red'),
         "header": Color("brown")
     }
     for i, page_num in enumerate(tree.keys()):
         img = self.pdf_to_img(page_num)
         draw = Drawing()
         draw.fill_color = Color('rgba(0, 0, 0, 0.0)')
         for clust in tree[page_num]:
             for (pnum, pwidth, pheight, top, left, bottom,
                  right) in tree[page_num][clust]:
                 draw.stroke_color = colors[clust]
                 draw.rectangle(left=left,
                                top=top,
                                right=right,
                                bottom=bottom)
                 draw.push()
                 draw.font_size = 20
                 draw.font_weight = 10
                 draw.fill_color = colors[clust]
                 if int(left) > 0 and int(top) > 0:
                     draw.text(x=int(left), y=int(top), body=clust)
                 draw.pop()
         draw(img)
         img.save(filename=html_path + filename_prefix + "_page_" + str(i) +
                  '.png')
         imgs.append(img)
     return imgs
Exemple #19
0
 def text_wrap(self,image):
     draw = Drawing()
     draw.font = 'wandtests/assets/League_Gothic.otf'
     draw.fill_color = Color(self.__getitem__('color'))
     draw.text_alignment = 'center'
     image.font_size = self.__getitem__('font_size')
     draw.text(int(self.__getitem__('width_place')*image.width), int(self.__getitem__('height_place')*image.height), self.__getitem__('quote'))
     draw(image)
     return image
Exemple #20
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)
Exemple #21
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)
Exemple #22
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
Exemple #23
0
 def _caption_akari(self):
     caption = 'わぁい{0} あかり{0}大好き'.format(self.text)
     drawing = Drawing()
     drawing.font = 'assets/fonts/rounded-mgenplus-1c-bold.ttf'
     drawing.font_size = self.width / 15
     text = fill(caption, 23)
     drawing.gravity = 'south'
     drawing.text_interline_spacing = drawing.font_size / -5
     offset = max(self.width / 400, 2)
     # first the shadow
     drawing.translate(offset, -offset)
     drawing.fill_color = Color('#000')
     drawing.fill_opacity = 0.5
     drawing.text(0, 0, text)
     # then the text
     drawing.translate(-offset, offset)
     drawing.fill_color = Color('#fff')
     drawing.fill_opacity = 1.0
     drawing.stroke_color = Color('#000')
     drawing.stroke_width = max(self.width / 600, 1)
     drawing.text(0, 0, text)
     return caption, drawing
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)
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
Exemple #27
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)
Exemple #28
0
def generate_meme(upper_text, lower_text, picture_name):
    MEME_FOLDER = "memes"
    MARGINS = [25, 65, 100, 135, 170]

    if not exists(join(getcwd(), MEME_FOLDER)):
        mkdir(join(getcwd(), MEME_FOLDER))

    main_image = Image(filename=picture_name)
    main_image.resize(
        500, int(
            ((main_image.height * 1.0) / (main_image.width * 1.0)) * 500.0))

    upper_text = "\n".join(wrap(upper_text,
                                get_warp_length(main_image.width))).upper()
    lower_text = "\n".join(wrap(lower_text,
                                get_warp_length(main_image.width))).upper()
    lower_margin = MARGINS[lower_text.count("\n")]

    text_draw = Drawing()

    text_draw.font = join(getcwd(), "impact.ttf")
    text_draw.font_size = 40
    text_draw.text_alignment = "center"
    text_draw.stroke_color = Color("black")
    text_draw.stroke_width = 3
    text_draw.fill_color = Color("white")

    if upper_text:
        text_draw.text(main_image.width / 2, 40, upper_text)
    if lower_text:
        text_draw.text(main_image.width / 2, main_image.height - lower_margin,
                       lower_text)

    text_draw(main_image)

    outname = "[MEME] " + picture_name
    main_image.save(filename=join(getcwd(), MEME_FOLDER, outname))

    # if sys.platform.startswith('darwin'):
    #     system('open "%s"' % (join(getcwd(), MEME_FOLDER, outname)))
    # elif name == 'nt':
    #     system('start "%s"' % (join(getcwd(), MEME_FOLDER, outname)))
    # elif name == 'posix':
    #     system('xdg-open "%s"' % (join(getcwd(), MEME_FOLDER, outname)))
    # else:
    #     pass
    return MEME_FOLDER + '/' + outname
Exemple #29
0
    def make_og_meme(self, top, bottom):
        """Generate an OG Meme
        """

        wand_t = Image(blob=self.image.read())
        MARGINS = [50, 130, 200, 270, 340]

        # Set a minimum size
        wand_t.resize(
            1024, int(((wand_t.height * 1.0) / (wand_t.width * 1.0)) * 1024.0))

        use_top = True
        use_bottom = True

        if top == ' ':
            use_top = False
        if bottom == ' ':
            use_bottom = False

        if use_top:
            upper_text = "\n".join(
                wrap(top, self.get_warp_length(int(wand_t.width)))).upper()
        if use_bottom:
            lower_text = "\n".join(
                wrap(bottom, self.get_warp_length(int(wand_t.width)))).upper()
            lower_margin = MARGINS[lower_text.count("\n")]

        text_draw = Drawing()

        text_draw.font = "fonts/Anton-Regular.ttf"
        text_draw.font_size = 70
        text_draw.text_alignment = "center"
        text_draw.stroke_color = Color("black")
        text_draw.stroke_width = 3
        text_draw.fill_color = Color("white")

        if use_top:
            text_draw.text(int(wand_t.width / 2), 80, upper_text)

        if use_bottom:
            text_draw.text(int(wand_t.width / 2),
                           int(wand_t.height - lower_margin), lower_text)

        text_draw(wand_t)

        return (wand_t)
Exemple #30
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
Exemple #31
0
def combine_images(*images: List[Union[str, bytes, WandImage]]) -> Image:
    with ThreadPool() as pool:
        images = pool.map(normalize_image, images)

    max_width = round(mean(img.width for img in images))
    max_height = round(mean(img.height for img in images))
    sum_width = max_width * len(images)

    canvas = WandImage(width=sum_width, height=max_height)
    resizer = ImageResizer(max_width, max_height)

    left = 0
    draw = Drawing()
    draw.fill_color = Color('white')
    draw.rectangle(left=0, top=0, right=canvas.width, bottom=canvas.height)
    draw(canvas)

    for img in images:
        if img.height < max_height:
            img = resizer.resize(img, max_height / img.height)

        if img.width < max_width:
            img = resizer.resize(img, max_width / img.width)
        elif img.width > max_width:
            # Do a bit of cropping so it's centered
            crop_left = round((img.width - max_width) / 2)
            crop_right = crop_left + max_width
            img.crop(crop_left, 0, crop_right, img.height)

        draw.composite(operator='over',
                       top=0, left=left,
                       width=img.width, height=img.height,
                       image=img)
        draw(canvas)
        left += img.width

    if DEBUG_IMAGE:  # pragma: no cover
        server_name = os.environ.get('DISPLAY', ':0')
        display(canvas, server_name=server_name)

    return Image(content=canvas.make_blob(format='png'),
                 content_type='image/png')
Exemple #32
0
def generar_meme(texto, nombre_imagen):
    imagen = Image(filename=nombre_imagen)
    imagen.resize(1024,
                  int(((imagen.height * 1.0) / (imagen.width * 1.0)) * 1024.0))

    texto = "\n".join(wrap(texto, get_length(imagen.width))).upper()

    text_draw = Drawing()

    text_draw.font = os.path.join(os.getcwd(), "impact.ttf")
    text_draw.font_size = 60
    text_draw.text_alignment = "center"
    text_draw.stroke_color = Color("black")
    text_draw.stroke_width = 3
    text_draw.fill_color = Color("white")

    if texto:
        text_draw.text(imagen.width * 60//100, imagen.height * 55//100, texto)

    text_draw(imagen)

    imagen.save(filename=os.path.join(os.getcwd(), "memes", "meme.jpg"))
Exemple #33
0
def create_line_img(x_start, x_finish, brush_width, params, img, filename):
    step = 1.01
    draw_img = Drawing()
    draw_img.stroke_color = Color("white")
    draw_img.fill_color = Color("white")
    draw_img.stroke_width = brush_width
    if x_start > x_finish:
        buf = x_start
        x_start = x_finish
        x_finish = buf
    x = x_start + step
    for i in range(3):
        while x < x_finish:
            x1 = x - step
            y1 = chosen_func(x1, params)
            y2 = chosen_func(x, params)
            draw_img.line((x1, y1), (x, y2))
            x = x + 2 * step
        step -= 0.5
        x = x_start + step
    draw_img.draw(img)
    img.save(filename=filename)
Exemple #34
0
    def process(self, area: os.DirEntry, city: os.DirEntry, pic: os.DirEntry,
                save_dir: str):
        # os.DirEntry.name is the picture's filename
        filename = pic.name

        # Store the absolute path of the current directory
        # so that we can return to it when we're done,
        # so that the calling function doesn't end up
        # with a working directory that is not the same
        # as the one it had before the call to process()
        return_dir = os.path.abspath(os.curdir)

        # os.path.splitext gives us both the file name and
        # the extension of the picture. We need the extension
        # because we're going to use it to tell Wand
        # (and, in turn, ImageMagick) what extension
        # to give to the image and we want to retain
        # the original one
        (name, extension) = os.path.splitext(pic)
        text = f'{city.name}({area.name})'
        save_name = f'{self.i}-{text}{extension}'

        if self.edit:
            with Image(filename=filename) as image:
                draw = Drawing()
                draw.fill_color = "white"
                draw.font_size = 90
                draw.gravity = "south_east"
                draw.text(30, 30, text)
                draw.draw(image)
                os.chdir(save_dir)
                image.save(filename=save_name)
            self.i = self.i + 1
        else:
            copyfile(pic.name, f"{save_dir}/{save_name}")

        os.chdir(return_dir)
Exemple #35
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")
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')
Exemple #37
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).
#
Exemple #38
0
    def draw_lip(self, top=False, bottom=False):
        if "back" not in self.faces:
            return None

        if not (top ^ bottom): # 1 and only 1 of top or bottom should be true
            return None

        # First draw a full mask with the lip shape
        lip_full_mask_image = Image(width=math.ceil(self.tuckbox['width'] * POINT_PER_MM),
                                    height=math.ceil(self.lip_size() * POINT_PER_MM))
        lip_full_draw = Drawing()

        lip_full_draw.scale(POINT_PER_MM, POINT_PER_MM)

        # This cannot be too "thin" or the floodfill later would spill over
        lip_full_draw.stroke_width = max(2 / POINT_PER_MM, RESOLUTION / (200 * POINT_PER_MM))

        lip_full_draw.fill_color = Color('white')
        lip_full_draw.color(0, 0, 'reset')
        lip_full_draw.draw(lip_full_mask_image)

        lip_full_draw.stroke_color = Color('black')

        # 1/2 left of lip
        lip_full_draw.bezier([(0, self.lip_size()),
                              (0, self.lip_size() - .75*self.lip_size()),
                              (.2 * self.tuckbox['width'],
                               self.lip_size() - self.lip_size()),
                              (.5 * self.tuckbox['width'], self.lip_size() - self.lip_size())])

        # 1/2 right of lip
        lip_full_draw.bezier([(self.tuckbox['width'], self.lip_size()),
                              (self.tuckbox['width'],
                               self.lip_size() - .75*self.lip_size()),
                              (.8 * self.tuckbox['width'],
                               self.lip_size() - self.lip_size()),
                              (.5 * self.tuckbox['width'], self.lip_size() - self.lip_size())])

        lip_full_draw.draw(lip_full_mask_image)

        lip_full_draw.fill_color = Color('black')
        lip_full_draw.border_color = Color('black')
        lip_full_draw.color(.5 * self.tuckbox['width'],
                            0.8*self.lip_size(), 'filltoborder')

        lip_full_draw.draw(lip_full_mask_image)

        if self.faces['back'][:1] == "#":
            lip_image = Image(width = lip_full_mask_image.width, height = lip_full_mask_image.height,
                            background = Color(self.faces['back']))
        else:
            # Prepare the front image
            angle = 180 if "back_angle" not in self.options else (self.options["back_angle"]+2)*90

            if bottom:
                angle = (angle + 180) % 360

            _, file_extension = os.path.splitext(self.faces['back'])
            tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=file_extension)
            self.resize_rotate_image(self.faces['back'], tmp_file.name, angle, math.ceil(self.tuckbox['width'] * POINT_PER_MM),
                            math.ceil(self.tuckbox['height'] * POINT_PER_MM))
            lip_image = Image(filename=tmp_file.name)
            lip_image.crop(top=lip_image.height - lip_full_mask_image.height)

        # u = image pixel
        # h = height
        # j = row
        # Radius of the hold is {self.tuckbox['width']*.1}
        # if value is 1 (or more_, it's white
        # Top is the tip of the lip, bottom is attached to the box
        # finger_hold_size_save is the row # at which it should be no attenuation below
        finger_hold_size_save = str(
            int(lip_image.height - math.ceil(self.tuckbox['width'] * POINT_PER_MM * 0.1)))
        lip_image = lip_image.fx(
            "j>"+finger_hold_size_save+"?u:1+(u-1)*(j/"+finger_hold_size_save+")")

        lip_image.composite(operator='lighten', image=lip_full_mask_image)

        if bottom:
            lip_image.rotate(180)

        return lip_image
Exemple #39
0
    def draw_box(self, progress_tracker=None):
        if not self.check_paper_layout():
            return None

        tuckbox_dimensions = ['width', 'height', 'depth']
        paper_dimensions = ['width', 'height']
        if ((not all(dimension in self.tuckbox for dimension in tuckbox_dimensions)) or
            (not all(dimension in self.paper for dimension in paper_dimensions))):
            return None

        # How much white space on the sides
        margin_height = (self.paper['height'] - self.pattern_height()) / 2
        margin_width = (self.paper['width'] - self.pattern_width()) / 2

        # Main box draw
        draw = Drawing()
        draw.scale(POINT_PER_MM, POINT_PER_MM)
        draw.stroke_color = Color('black')
        draw.stroke_width = RESOLUTION / (200 * POINT_PER_MM)
        draw.fill_opacity = 0
        draw.translate(margin_width,
                       margin_height + self.lip_size() + self.tuckbox['depth'])
        draw.push()

        # Finger holds draw
        finger_draw = Drawing(draw)
        finger_draw.fill_opacity = 1
        finger_draw.fill_color = Color('white')
        finger_draw.push()

        # Dashed draw
        dashed_draw = Drawing(draw)
        dash_array = [min(self.tuckbox['depth'], self.tuckbox['width'],
                          self.tuckbox['height'])/13] * 2
        dashed_draw.stroke_color = Color('rgb(100,100,100)')
        dashed_draw.fill_opacity = 0
        dashed_draw.stroke_width = RESOLUTION / (300 * POINT_PER_MM)
        dashed_draw.stroke_dash_array = dash_array
        dashed_draw.stroke_dash_offset = 1

        # Folding guides draw
        folding_guides_draw = Drawing()
        folding_guides_draw.scale(POINT_PER_MM, POINT_PER_MM)
        folding_guides_draw.stroke_color = Color('black')
        folding_guides_draw.stroke_width = RESOLUTION / (200 * POINT_PER_MM)

        back_draw = Drawing(draw)
        back_dashed_draw = Drawing(dashed_draw)
        back_folding_guides_draw = Drawing(folding_guides_draw)

        if progress_tracker is not None:
            progress_tracker(5)

        two_openings = 'two_openings' in self.options and self.options['two_openings']
        two_pages = 'two_pages' in self.options and self.options['two_pages']

        dash_array = [min(self.tuckbox['depth'], self.tuckbox['width'],
                          self.tuckbox['height'])/13] * 2

        #
        # Draw the box (or the first page)
        #
        self.draw_front(draw, dashed_draw, two_openings)

        if two_pages:
            offset_left_to_back = self.tuckbox['depth']
        else:
            offset_left_to_back = self.tuckbox['depth']*2 + self.tuckbox['width']

        self.draw_back(offset_left_to_back, back_draw, back_dashed_draw, finger_draw, two_openings)

        if two_pages:
            back_draw.polyline([(self.tuckbox['depth'], 0),
                           (self.tuckbox['depth'] * 0.2, 0),
                           (self.tuckbox['depth'] * 0.2, self.tuckbox['height']),
                           (self.tuckbox['depth'], self.tuckbox['height'])])
            draw.line((self.tuckbox['depth']*2 + self.tuckbox['width'], 0),
                      (self.tuckbox['depth']*2 + self.tuckbox['width'], self.tuckbox['height']))

        if progress_tracker is not None:
            progress_tracker(10)

        # Create the image
        image = Image(width=math.ceil(self.paper['width'] * POINT_PER_MM),
                      height=math.ceil(self.paper['height'] * POINT_PER_MM),
                      background=Color('white'))
        image.resolution = RESOLUTION
        image.unit = 'pixelsperinch'

        if two_pages:
            image2 = Image(width=math.ceil(self.paper['width'] * POINT_PER_MM),
                        height=math.ceil(self.paper['height'] * POINT_PER_MM),
                        background=Color('white'))
            image2.resolution = RESOLUTION
            image2.unit = 'pixelsperinch'
        else:
            image2 = image

        # Draw the faces
        self.draw_faces(image, progress_tracker, with_back = not two_pages)
        if two_pages:
            self.draw_faces(image2, progress_tracker, only_back=True)

        # Draw the lip(s)
        lip = self.draw_lip(top=True)
        if lip is not None:
            image.composite(lip,
                            math.floor((margin_width + self.tuckbox['depth']) * POINT_PER_MM),
                            math.floor((margin_height) * POINT_PER_MM))

        if two_openings:
            lip = self.draw_lip(bottom=True)
            if lip is not None:
                image.composite(lip,
                                math.floor((margin_width + self.tuckbox['depth']) * POINT_PER_MM),
                                math.floor((margin_height + self.tuckbox['depth']*2 + self.lip_size() + self.tuckbox['height']) * POINT_PER_MM))

        if progress_tracker is not None:
            progress_tracker(80)

        # Draw all the lines over
        draw.draw(image)
        back_draw.draw(image2)

        finger_draw.draw(image2)
        self.draw_watermark(image)
        if two_pages:
            self.draw_watermark(image2)

        if progress_tracker is not None:
            progress_tracker(90)

        if "folds_dashed" in self.options and self.options["folds_dashed"]:
            dashed_draw.draw(image)
            back_dashed_draw.draw(image2)

        if "folding_guides" in self.options and self.options["folding_guides"]:
            front_vertical_folds = [margin_width + self.tuckbox['depth'],
                              margin_width +
                              self.tuckbox['depth'] + self.tuckbox['width']]
            if not two_pages:
                front_vertical_folds.extend([margin_width +
                                       self.tuckbox['depth']*2 + self.tuckbox['width'],
                                       margin_width + self.tuckbox['depth']*2 + self.tuckbox['width']*2])

            back_vertical_folds = [margin_width + self.tuckbox['depth'],
                                  margin_width +
                                  self.tuckbox['depth'] + self.tuckbox['width']]

            front_horizontal_folds = [margin_height + self.lip_size(),
                                margin_height + self.lip_size() +
                                self.tuckbox['depth'],
                                margin_height + self.lip_size() +
                                self.tuckbox['depth'] + self.tuckbox['height']]

            if two_openings:
                front_horizontal_folds.append(margin_height + self.lip_size() +
                                        self.tuckbox['depth'] * 2 + self.tuckbox['height'])
                back_horizontal_folds = []
            else:
                back_horizontal_folds = [margin_height + self.lip_size() +
                                        self.tuckbox['depth'] + self.tuckbox['height']]

            self.draw_folds(folding_guides_draw, front_vertical_folds, front_horizontal_folds, margin_height, margin_width)
            self.draw_folds(back_folding_guides_draw, back_vertical_folds, back_horizontal_folds, margin_height, margin_width)

            folding_guides_draw.draw(image)
            back_folding_guides_draw.draw(image2)

        if progress_tracker is not None:
            progress_tracker(100)

        if not two_pages:
            image2 = None

        return image, image2
Exemple #40
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
Exemple #41
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
    # ----------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(addx), y=abs(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])+')')
    # print('font_color =' + 'rgb('+str(color2[0])+','+str(color2[1])+','+str(color2[2])+')')
    draw.text(x=0, y=0, body=word)
    draw.draw(baseImage)
    # --------------------------------------------------------------
Exemple #43
0
def banner(temp, loss, resultplt=None, date=""):
    txt_color = "white"
    with Image(width=140, height=230, background="transparent") as img:
        draw = Drawing()
        draw.font = 'font/OpenSans-Bold.ttf'
        draw.font_size = 14
        draw.font_antialias = True
        draw.text_alignment = 'center'
        draw.fill_color = txt_color
        draw.text(70, 14, 'Moscow')
        draw(img)

        draw = Drawing()
        draw.font = 'font/OpenSans-Bold.ttf'
        draw.font_size = 10
        draw.font_antialias = True
        draw.text_alignment = 'center'
        draw.fill_color = txt_color
        draw.text(70, 28, date)
        draw(img)

        draw = Drawing()
        draw.font = 'font/OpenSans-SemiBold.ttf'
        draw.font_size = 50
        draw.font_antialias = True
        draw.text_alignment = 'center'
        draw.fill_color = txt_color
        draw.text(70, 80, "%+d" % float(temp) + '°')
        draw(img)

        if resultplt:
            image_data = BytesIO()
            resultplt.axis('off')
            resultplt.gcf().set_size_inches(1.4, 0.7)
            resultplt.gcf().set_dpi(100)
            resultplt.tight_layout()
            resultplt.savefig(image_data, format='png', transparent=True)
            image_data.seek(0)
            result_image = Image(file=image_data)
            img.composite(image=result_image, left=0, top=110)

            draw = Drawing()
            draw.font = 'font/OpenSans-Bold.ttf'
            draw.font_size = 14
            draw.font_antialias = True
            draw.text_alignment = 'center'
            draw.fill_color = txt_color
            draw.text(70, 115, '2020')
            draw(img)

        for i, t in enumerate([
                "loss: " + str(loss), "input: 9 params",
                "train data: 16430 rows"
        ]):
            draw = Drawing()
            draw.font = 'font/OpenSans-Light.ttf'
            draw.font_size = 10
            draw.font_antialias = True
            draw.fill_color = txt_color
            draw.text(4, 190 + (i * 12), t)
            draw(img)

        img.save(filename='weather.png')
Exemple #44
0
def makedrawing():
    draw = Drawing()
    draw.fill_color = Color('white')
    draw.stroke_color = Color('black')
    draw.stroke_width = 1
    return draw
Exemple #45
0
			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'])
		draw(img)

		draw = Drawing()
		draw.font = 'wandtests/assets/League_Gothic.otf'
		draw.font_size = 20
Exemple #46
0
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
draw_01.fill_color = Color('black')
draw_01.text(0, int(metrics_01.text_height), "21")
draw_01(image_01)
Exemple #47
0
                    #print hex(ord(mc_v_data[idx]))
                    color = ord(mc_v_data[idx]) & 0x0f
                    #color = bgcolor
                elif code == "10":
                    #print hex(ord(mc_v_data[idx]))
                    color = ord(mc_v_data[idx]) >> 4
                    #color = bgcolor
                elif code == "11":
                    #print hex(ord(mc_c_data[idx]))
                    color = ord(mc_c_data[idx]) & 0x0f
                    #color = bgcolor

                color_t = pepto[color]
                color_s = "rgb(" + str(color_t[0]) +  "," + str(color_t[1]) + "," + str(color_t[2]) +  ")"

                drw.fill_color = Color(color_s)
                drw.stroke_line_cap = 'square'
                drw.point(x,y)

drw(img)
img.save(filename='test.jpg')

# No dupe coords
print "# coords written:", len(coords)
assert len(coords) == len(set(coords))

# No dupe offs
print "# offs read:", len(offs)
assert len(offs) == len(set(offs))

# Accesses to color/screen RAM
Exemple #48
0
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')
Exemple #49
0
    # ----------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(addx), y=abs(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]) + ')')
    # print('font_color =' + 'rgb('+str(color2[0])+','+str(color2[1])+','+str(color2[2])+')')
    draw.text(x=0, y=0, body=word)
    draw.draw(baseImage)