def draw_text(draw: ImageDraw, image: Image, font, text="Text example", gravity="South", fill=(0, 0, 0), padding=5, margin=10): text_width, text_height = draw.textsize(text, font=font) gravity = gravity.lower() if gravity == 'south': x = (image.width - text_width) // 2 y = image.height - text_height - margin - padding elif gravity == 'north': x = (image.width - text_width) // 2 y = margin + padding elif gravity == 'center': x = (image.width - text_width) // 2 y = (image.height - text_height) // 2 elif gravity == 'southwest': x = margin + padding y = image.height - text_height - margin - padding elif gravity == 'southeast': x = image.width - margin - padding - text_width y = image.height - text_height - margin - padding elif gravity == 'northwest': x = y = margin + padding elif gravity == 'northeast': x = image.width - margin - padding - text_width y = margin + padding else: x = y = 0 draw.rectangle((x - padding, y - padding, x + text_width + padding, y + text_height + padding), fill=fill) draw.text((x, y), text=text, font=font)
def draw_activity(self, draw: ImageDraw, name: str, time: str, progress: float, x: int, y: int): title_font_size = 40 text_progress_margin = 25 progress_end_y = y + BasicImageCreator.PROGRESS_BAR_HEIGHT + text_progress_margin progress_start_xy = (x, y + text_progress_margin) background_end_xy = (x + BasicImageCreator.PROGRESS_BAR_WIDTH, progress_end_y) foreground_end_xy = (x + BasicImageCreator.PROGRESS_BAR_WIDTH * progress, progress_end_y) draw.rectangle( (progress_start_xy, background_end_xy), fill=self.data_repository.get_setting("progress_background_color")) draw.rectangle( (progress_start_xy, foreground_end_xy), fill=self.data_repository.get_setting("progress_foreground_color")) # Draw activity title draw.text( (x, y - title_font_size), name, font=ImageFont.truetype(self.get_font("semi_bold"), title_font_size), fill=self.data_repository.get_setting("activity_title_color")) # Draw activity time draw.text((x + BasicImageCreator.PROGRESS_BAR_WIDTH, y - 20), BasicImageCreator.time_as_str(time), font=ImageFont.truetype(self.get_font("bold"), 30), fill=self.data_repository.get_setting("activity_time_color"), anchor="rt")
def _render_departure_font( self, draw: ImageDraw, y: int, departure: departure.Departure, font: FreeTypeFont, ) -> int: _, dst_height = draw.textsize( "{} {}".format(departure.line_number, departure.destination), font=font ) time_width, time_height = draw.textsize(departure.display_time, font=font) dst_y = y + 5 dst_x = 0 # set border time_x = self._d_width - time_width - 2 time_y = y + 5 draw.text( (dst_x, dst_y), "{} {}".format(departure.line_number, departure.destination), fill="white", font=font, ) draw.text((time_x, time_y), departure.display_time, fill="white", font=font) return dst_height
def draw(self, draw: ImageDraw): if not self.show: return horizontal_pad = self.width // 25 bottom_pad = self.height // 4 draw.line((self.abs_col + horizontal_pad, self.abs_row + self.height - bottom_pad, self.abs_col + self.width - horizontal_pad, self.abs_row + self.height - bottom_pad), fill=self.foreground) text_w, text_h = self.font.getsize(' ') polygon_pts = ((self.abs_col + horizontal_pad, self.abs_row + self.height - bottom_pad), (self.abs_col + horizontal_pad, self.abs_row + self.height - bottom_pad - text_h), (self.abs_col + horizontal_pad + text_w * 8, self.abs_row + self.height - bottom_pad - text_h), (self.abs_col + horizontal_pad + text_w * 9, self.abs_row + self.height - bottom_pad)) date_str = datetime.datetime.strftime(self.date, ' %b %d') draw.polygon(polygon_pts, fill=self.foreground) draw.text((self.abs_col + horizontal_pad, self.abs_row + self.height - bottom_pad - text_h), date_str, fill=self.background, font=self.font) event_max_chars = (self.width - 2 * horizontal_pad) * 4 // 5 // text_w if len(self.event) > event_max_chars: self.event = self.event[:event_max_chars - 3] + '...' draw.text( (self.abs_col + (self.width - 2 * horizontal_pad) // 5 + horizontal_pad, self.abs_row + self.height - bottom_pad - text_h), self.event, fill=self.foreground, font=self.font)
def draw_title(self, draw: ImageDraw, date: str): draw.text( (140, 134), f"Coding statistics of {date}", font=ImageFont.truetype(self.get_font("semi_bold"), 40), fill=self.data_repository.get_setting("title_color"), )
def dessiner_texte(crayon: ImageDraw, texte: str, police: ImageFont, taille_fenetre: Dimensions, origine: Point = Point(0, 0), couleur_texte=COULEUR_PAR_DEFAUT_TEXTE, alignement_horizontal=AlignementHorizontal.GAUCHE, alignement_vertical=AlignementVertical.CENTRE): """ autheur: Nicolas Création de l’image au format 'rgb' avec la couleur de fond passé en parametre """ taille_texte = calculer_taille_texte(texte, police) if alignement_horizontal == AlignementHorizontal.DROITE: x = origine.x + taille_fenetre.longueur - taille_texte.longueur elif alignement_horizontal == AlignementHorizontal.CENTRE: x = origine.x + (taille_fenetre.longueur - taille_texte.longueur) // 2 else: x = origine.x if alignement_vertical == AlignementVertical.BAS: y = origine.y + taille_fenetre.longueur - taille_texte.longueur elif alignement_vertical == AlignementVertical.CENTRE: y = origine.y + (taille_fenetre.largeur - taille_texte.largeur) // 2 else: y = origine.y p = (x, y) crayon.text(p, texte, fill=couleur_texte.format_rgb(), font=police)
def __dessiner_entete_nom_mois(self, origine: Point, crayon: ImageDraw): """ Dessine l'en-tête du mois :param origine: le point d'insértion de l'en-tête :param crayon: l'outil de dessin :param couleur_titre: la couleur du texte du nom de mois """ crayon.rectangle( (origine.to_tuple(), origine.deplacer( self.taille_entete_nom).to_tuple()), fill=self.couleur_fond_entete.value) if self.inclure_annee: annee_str = str(self.donnees.annee) taille_annee_mois = calculer_taille_texte( annee_str, police=CONST.POLICE_ANNEE_ENTETE_MOIS) pt_ins_annee_mois = (origine.x + self.taille_entete_nom.longueur - taille_annee_mois.longueur, origine.y) crayon.text(pt_ins_annee_mois, annee_str, fill=self.couleur_titre.value, font=CONST.POLICE_ANNEE_ENTETE_MOIS) # création d’un objet 'dessin' qui permet de dessiner sur l’image dessiner_texte(crayon, self.nom_mois, CONST.POLICE_NOM_MOIS, self.taille_entete_nom, origine, self.couleur_titre, AlignementHorizontal.CENTRE)
def draw_text_on_image( draw: ImageDraw, text: str, font: ImageFont, height: int, width: int, heigh_offset: int, width_offset: int, ): """Draw given text on the given image. Args: draw (ImageDraw): The ImageDraw object using which text will be drawn text (str): Text to draw on the image font (ImageFont): Font to be used height (int): Height of the image width (int): Width of the image heigh_offset (int): Height offset from the centre width_offset (int): Width offset from the centre """ w, h = draw.multiline_textsize(text, font, spacing=10) left = width_offset + ((width - w) * 0.5) top = heigh_offset + ((height - h) * 0.5) draw.text( (left, top), text, random.choice(COLOR_OPTIONS), font=font, spacing=10, stroke_width=3, stroke_fill="black", )
def set_text(self, __image: ImageDraw, img_width, img_height) -> list: font_size = random.choice(range(self.font_size[0], self.font_size[1])) font_num = random.choice(range(self.fonts_num[0], self.fonts_num[1])) max_width = int(img_width / font_num) max_height = int(img_height) font_type = random.choice(self.fonts_list) try: font = ImageFont.truetype(font_type, font_size) except OSError: del self.fonts_list[self.fonts_list.index(font_type)] raise Exception("{} opened fail") labels = [] for idx in range(font_num): fw = range(int(max_width - font_size)) if len(fw) > 0: x = max_width * idx + random.choice(fw) else: x = max_width * idx y = random.choice(range(int(max_height - font_size))) f = random.choice(self.sample) labels.append(f) __image.text((x, y), f, font=font, fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) return labels
def draw_total_time(self, draw: ImageDraw, total_time): draw.text( (140, 189), BasicImageCreator.time_as_str(total_time), font=ImageFont.truetype(self.get_font("extra_bold"), 60), fill=self.data_repository.get_setting("total_time_color"), )
def draw_box( draw: ImageDraw, box: Tuple[float, float, float, float], img_width: int, img_height: int, text: str = "", color: Tuple[int, int, int] = (255, 255, 0), ) -> None: """ Draw a bounding box on and image. The bounding box is defined by the tuple (y_min, x_min, y_max, x_max) where the coordinates are floats in the range [0.0, 1.0] and relative to the width and height of the image. For example, if an image is 100 x 200 pixels (height x width) and the bounding box is `(0.1, 0.2, 0.5, 0.9)`, the upper-left and bottom-right coordinates of the bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates). """ line_width = 5 y_min, x_min, y_max, x_max = box (left, right, top, bottom) = ( x_min * img_width, x_max * img_width, y_min * img_height, y_max * img_height, ) draw.line( [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)], width=line_width, fill=color, ) if text: draw.text((left + line_width, abs(top - line_width)), text, fill=color)
def get_code(request): mode = 'RGB' size = (200, 100) image = Image.new(mode=mode, size=size, color=rand_color()) image_draw = ImageDraw(image, mode=mode) font = ImageFont.truetype(code_font, 80) text = rand_wd().lower() request.session['verify_code'] = text for i in range(4): image_draw.text((45 * i + randrange(20), randrange(30)), text[i], fill=rand_color(), font=font) for i in range(6000): image_draw.point((randrange(201), randrange(101)), rand_color()) for i in range(randrange(3)): xy = ((randrange(201), randrange(101)), (randrange(201), randrange(101))) image_draw.line(xy, fill=rand_color(), width=2) fp = BytesIO() image.save(fp, 'png') return HttpResponse(fp.getvalue(), content_type='image/png')
def draw_captions(self, canvas: ImageDraw, captions, settings): for setting in settings[1:]: caption = captions.pop(0) lines = wrap(caption, setting.get("wrap", settings[0].get("wrap", 20))) real_line_height = setting.get("font_size", settings[0].get("font_size", self.FONT_SIZE)) + 5 lines_count = len(lines) for line_index, line in enumerate(lines): x, y = setting.get("position") font = ImageFont.truetype("resources/fonts/lato.ttf", setting.get("font_size", settings[0].get("font_size", self.FONT_SIZE))) line_width, line_height = canvas.textsize(line, font=font) if setting.get("center", settings[0].get("center", True)): x -= line_width / 2 if setting.get("center_vertical", settings[0].get("center_vertical", False)): y -= (lines_count * real_line_height) / 2 shadow_color = setting.get("shadow_color", settings[0].get("shadow_color", None)) real_y = y + line_index * real_line_height if shadow_color is not None: shadow_size = setting.get("shadow_size", settings[0].get("shadow_size", 3)) for offset_x in range(-shadow_size, shadow_size + 1): for offset_y in range(-shadow_size, shadow_size + 1): canvas.text((x + offset_x, real_y + offset_y), line, font=font, fill=shadow_color) canvas.text((x, real_y), line, font=font, fill=setting.get("color", settings[0].get("color", self.BLACK)))
def _draw_footer(self, draw: ImageDraw) -> None: y = self._display.height - self._display.character_height * 2 - 1 draw.line([(0, y), (self._display.width, y)], fill=(255, 255, 255), width=1) y += 1 for l in self._multiline_split(self._selections[self._selected].description, 2): draw.text((1, y), l, fill=(255, 255, 255)) y += self._display.character_height
def render_text(self, _: Image, draw: ImageDraw, draw_property: Mapping, bounding_box: Tuple[Tuple[int, int], Tuple[int, int]], current_x: int, current_y: int, backwards: bool) -> Tuple[int, int]: font = ImageFont.truetype(draw_property["font"], draw_property["font_size"]) text = self.properties.get(draw_property["property"]) current_x, current_y = self.resolve_position(draw_property["position"], bounding_box, current_x, current_y) if text is not None: background = self.properties.get(draw_property["background_property"]) if background is None: background = draw_property["background_default"] text_color = self.properties.get(draw_property["text_color_property"]) if text_color is None: text_color = draw_property["text_color_default"] text_width, text_height = draw.textsize(text, font) desired_width = draw_property["size"][0] if draw_property["size"][0] != "auto" else text_width desired_height = draw_property["size"][1] if draw_property["size"][1] != "auto" else text_height if backwards: current_x -= desired_width draw.rectangle(((current_x, current_y), (current_x + desired_width, current_y + desired_height)), fill=background) # CodeReview: center between current_y and bottom of bounding box x_coord = (current_x + (desired_width - text_width) // 2) if draw_property["centered_width"] else current_x y_coord = (current_y + (desired_height - text_height) // 2) if draw_property["centered_height"] \ else current_y draw.text((x_coord, y_coord), text, fill=text_color, font=font) current_x += desired_width elif draw_property["required"]: raise Exception(f"Missing required property: {draw_property['property']} from card {self.properties}") return current_x, current_y
def frame(draw: ImageDraw, delta): # global x # side = 16 # draw.line([(x, 127/2), (x+side, 127/2)], fill = "WHITE", width = side) # x = (x + 1) % (127-side) draw.text((0, 12), '500Mbps', fill="WHITE", font=font)
def draw_text(self, draw: ImageDraw, time: str, progress_height: int, time_width: int, time_height: int, font_time: ImageFont): draw.text(((self.width - time_width) / 2, (self.height - time_height - progress_height) / 2), time, self.font_color, font=font_time, align='center')
def _drawSingleChinese(self, x: int, y: int, singleCharacter: str, draw: ImageDraw): text_size = self.__font_size font = ImageFont.truetype(font=self.fontPath, size=text_size, encoding='utf-8') draw.text((x, y), singleCharacter, font=font, fill=(28, 28, 28, 255)) return text_size
def _insert_text(draw: ImageDraw, x, y, text, color='rgb(0, 0, 0)', font_file='fonts/Roboto-Bold.ttf', font_size=12): text = str(text) font = ImageFont.truetype(font_file, size=font_size) draw.text((x, y), text, fill=color, font=font) return draw
def draw(self, draw: ImageDraw): weather_text = self.weather xoff = self.x yoff = self.y font = self.DEFAULT_FONT draw.text((xoff, yoff), weather_text, font=font)
def mark_image(self, draw: ImageDraw, captions): BOARD_X, BOARD_Y = (80, 70) lines = wrap(captions[0], 20) for line_index, line in enumerate(lines): draw.text((BOARD_X, BOARD_Y + line_index * 25), line, font=self.small_font, fill=self.BLACK)
def add_field(self, image_draw: ImageDraw, text: str, coord: str, font_size: int, color: str): font = ImageFont.truetype("fonts/arial.ttf", size=font_size) image_draw.text(self.coord_to_tuple(coord), text, fill=self._hex_to_rgb(color), font=font) return image_draw
def _render_alert(self, draw: ImageDraw) -> None: font = self._fonts["alert"] alert_width, alert_height = draw.textsize(self._display_alert[:30], font=font) alert_x = 0 alert_y = self._d_height - alert_height draw.text((alert_x, alert_y), self._display_alert[:30], fill="white", font=font)
def add_num(img): draw = ImageDraw(img) myfont = ImageFont.truetype('/Library/Fonts/Arial Italic.ttf ', size=40) fillcolor = "#ff0000" width, height = img.size draw.text((width - 40, 0), '99', font=myfont, fill=fillcolor) img.save('result.jpg', 'jpeg') return 0
def _pasteMoney(offset, money: str, color: list, draw: ImageDraw): font = ImageFont.truetype(os.sep.join( (os.getcwd(), "resource", "ttf", "msjh.ttc")), size=60, encoding='utf-8') money = money[::-1] result = ','.join([money[i:i + 3] for i in range(0, len(money), 3)]) result = "Coin. " + result[::-1] + ".00" draw.text(offset, result, fill=tuple(color), font=font, stroke_width=1)
def draw(self, tag_num=1): tag_size = max(self.img.size[0], self.img.size[1]) / 5 tag_str = str(tag_num) if tag_num < 100 else '99+' font = ImageFont.truetype("/Library/Fonts/Arial.ttf", tag_size) px = self.img.size - font.getsize(tag_size)[0] draw_pen = ImageDraw(self.img) draw_pen.text((px, 0), tag_str, (255, 0, 0), font) self.img.save('face' + tag_str + '.jpg') return True
def _pasteName(offset, username: str, color: list, draw: ImageDraw): font = ImageFont.truetype(os.sep.join( (os.getcwd(), "resource", "ttf", "msjh.ttc")), size=60, encoding='utf-8') draw.text(offset, username, fill=tuple(color), font=font, stroke_width=1)
def _draw_selections(self, draw: ImageDraw) -> None: y = 2 + self._display.character_height for i, v in enumerate(self._selections): # only show items that fit if y < (self._display.height - self._display.character_height * 3): # has room still if self._selected == i: draw.rectangle([(0, y), (self._display.width, y + self._display.character_height)], fill=(255, 0, 0)) draw.text((1, y), v.title, fill=(255, 255, 255)) y += self._display.character_height
def draw_watermark(self, draw: ImageDraw, max_height): username = self.data_repository.get_setting("username").strip() title = "by code-time" if username != "": title += f" for {username}" draw.text((140, max_height - 200), title, font=ImageFont.truetype(self.get_font("semi_bold"), 30), fill=self.data_repository.get_setting("watermark_color"))
def renderClock(draw: ImageDraw, width, height): t = time.localtime() current_time = time.strftime("%H:%M:%S", t) textwidth, _ = draw.textsize(current_time, fontBoldTall) draw.text( ((width / 2) - (textwidth / 2), 0), current_time, fill="yellow", font=fontBoldTall, )
def PrintText(self, text): # led.draw_text2(x-axis, y-axis, whatyouwanttoprint, size) < Understand? # So led.drawtext2() prints simple text to the OLED display like so: #text = 'Hello!' # Create the image to write to the display # THIS MAY NEED TO CHANGE BASED ON STRING LENGTH! image = Image.new('1', (128, 64)) draw = ImageDraw(image) draw.text((0, 0), text, font=ImageFont.load_default(), fill=255) # Clear the Display self.led.clear() self.led.display() # Write the text-based image to the display self.led.image(image) self.led.display()
def generate_captcha(request): path = '.' im = Image.new('RGBA', (200, 50), (0, 0, 0, 0)) draw = ImageDraw(im) number = '' margin_left, margin_top = 0, 0 colnum = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') i = 0 while i < 6: font_color = '#' + str(random.randint(0,9)) y = 0 while y < 5: rand = random.choice(colnum) font_color = font_color + rand y += 1 rand_x11 = random.randint(0, 100) rand_x12 = random.randint(100, 200) rand_y11 = random.randint(0, 50) rand_y12 = random.randint(0, 50) draw.line((rand_x11, rand_y11, rand_x12, rand_y12), fill='#a9a6a6') font_rand = str(random.randint(1, 10)) font_size_rand = random.randint(30, 40) font = ImageFont.truetype(path + "fonts/" + font_rand + ".ttf", font_size_rand) a = str(random.randint(0, 9)) draw.text((margin_left, margin_top), a, fill=str(font_color), font=font) rand_x11 = random.randint(0, 100) rand_x12 = random.randint(100, 200) rand_y11 = random.randint(0, 50) rand_y12 = random.randint(0, 50) draw.line((rand_x11, rand_y11, rand_x12, rand_y12), fill="#a9a6a6") margin_left = margin_left + random.randint(20, 35) margin_top = random.randint(0, 20) i += 1 number += a salt = "$@!SAf*$@)ASFfacnq==124-2542SFDQ!@$1512czvaRV" key = md5(str(number + salt)).hexdigest() output = StringIO() im.save(output, format="PNG") contents = output.getvalue().encode("base64").replace("\n", "") img_tag = '<img value="' + key + '" src="data:image/png;base64,{0}">'.format(contents) output.close() return img_tag
from PIL import Image, ImageDraw, ImageFont num = str(5) img = Image.open('shenle.png') h, l = img.size font = ImageFont.truetype('/usr/share/fonts/truetype/droid/DroidSans.ttf', 30) draw = ImageDraw(img) draw.text((h*0.8, l*0.2), num, font=font, fill(255, 33, 33)) img.save('shenle5.png', 'png')