mod letter

This commit is contained in:
l.gabrysiak 2025-03-02 13:35:35 +01:00
parent db9ed8f878
commit dd65611fff
1 changed files with 25 additions and 8 deletions

View File

@ -355,22 +355,39 @@ class UsersTable:
image = Image.new('RGB', size, color=background_color) image = Image.new('RGB', size, color=background_color)
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
font_size = min(size) // 2 # Ustawienie koloru czcionki na biały
try: text_color = (255, 255, 255)
font = ImageFont.truetype("arial.ttf", font_size)
except IOError:
font = ImageFont.load_default()
# Użyj font.getbbox() zamiast draw.textsize() # Funkcja do obliczania rozmiaru czcionki
def get_font_size(image_size, text, font_path, target_percentage=0.8):
font_size = 1
font = ImageFont.truetype(font_path, font_size)
while font.getbbox(text)[2] < target_percentage * image_size[0] and \
font.getbbox(text)[3] < target_percentage * image_size[1]:
font_size += 1
font = ImageFont.truetype(font_path, font_size)
return font_size - 1
try:
font_path = "arial.ttf"
font_size = get_font_size(size, letter, font_path)
font = ImageFont.truetype(font_path, font_size)
except IOError:
# Jeśli Arial nie jest dostępny, użyj czcionki domyślnej
font = ImageFont.load_default()
# Dla czcionki domyślnej możemy potrzebować innej metody określania rozmiaru
font_size = min(size) // 2 # To jest przybliżenie, może wymagać dostosowania
# Obliczanie pozycji tekstu
bbox = font.getbbox(letter) bbox = font.getbbox(letter)
text_width = bbox[2] - bbox[0] text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1] 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)
text_color = (255 - background_color[0], 255 - background_color[1], 255 - background_color[2]) # Rysowanie litery
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()