mod letter

This commit is contained in:
l.gabrysiak 2025-03-02 13:18:50 +01:00
parent 0cbecb557d
commit db9ed8f878
1 changed files with 5 additions and 11 deletions

View File

@ -348,35 +348,29 @@ class UsersTable:
@staticmethod @staticmethod
def generate_image_base64(letter, size=200): def generate_image_base64(letter, size=200):
# Upewniamy się, że size jest krotką
if isinstance(size, int): if isinstance(size, int):
size = (size, size) size = (size, size)
elif not isinstance(size, (list, tuple)) or len(size) != 2:
raise ValueError("Size must be an integer or a tuple of two integers")
# Tworzenie obrazu z losowym kolorem tła
background_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) background_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
image = Image.new('RGB', size, color=background_color) image = Image.new('RGB', size, color=background_color)
# Tworzenie obiektu do rysowania
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
# Ładowanie czcionki
font_size = min(size) // 2 font_size = min(size) // 2
try: try:
font = ImageFont.truetype("arial.ttf", font_size) font = ImageFont.truetype("arial.ttf", font_size)
except IOError: except IOError:
font = ImageFont.load_default() font = ImageFont.load_default()
# Obliczanie pozycji tekstu # Użyj font.getbbox() zamiast draw.textsize()
text_width, text_height = draw.textsize(letter, font=font) bbox = font.getbbox(letter)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
position = ((size[0] - text_width) / 2, (size[1] - text_height) / 2) position = ((size[0] - text_width) / 2, (size[1] - text_height) / 2)
# Rysowanie litery
text_color = (255 - background_color[0], 255 - background_color[1], 255 - background_color[2]) text_color = (255 - background_color[0], 255 - background_color[1], 255 - background_color[2])
draw.text(position, letter, font=font, fill=text_color) draw.text(position, letter, font=font, fill=text_color)
# Konwersja obrazu do base64
buffered = io.BytesIO() buffered = io.BytesIO()
image.save(buffered, format="PNG") image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode() img_str = base64.b64encode(buffered.getvalue()).decode()