Сейчас я напишу тебе программу на языке python, на входе которой словарь с данными, а на…
- User
Сейчас я напишу тебе программу на языке python, на входе которой словарь с данными, а на выходе рисуется картинка, содержащая таблицу. Программа: import pytz import datetime import time import requests import textwrap
from babel.dates import format_date, format_datetime, format_time, get_timezone, UTC
from PIL import Image, ImageDraw, ImageFont
def draw_date_header(image, text, font, row_height, start_coordinate_x, start_coordinate_y): overlay = Image.new('RGBA', image.size, (255, 255, 255, 0)) draw_overlay = ImageDraw.Draw(overlay) # Create a context for drawing things on it. original_image = image
cell_text = text # Находим размер текста с помощью метода font.getbbox text_bbox = font.getbbox(cell_text) text_height = text_bbox[3] - 20 text_x = start_coordinate_x text_y = start_coordinate_y + (row_height - text_height) // 2 # Рисуем тень shadow_color = (0, 0, 0) shadow_x = text_x + 2 shadow_y = text_y + 2 draw_overlay.text((shadow_x, shadow_y), text, fill=shadow_color, font=font) draw_overlay.text((text_x, text_y), cell_text, fill=(255, 255, 255), font=font) # Alpha composite these two images together to obtain the desired result. original_image = Image.alpha_composite(original_image, overlay) image = original_image return imagedef find_table_width(column_widths, column_spacing): cell_width = 0 for i in range(0, len(column_widths)):
cell_width = cell_width + column_widths[i] + column_spacing return cell_widthdef add_weather_icon(image, weather_icon, cell_width, row_height, start_coordinate_x, start_coordinate_y): cell_image = Image.open(weather_icon) cell_image.thumbnail((40, 40)) cell_image_width, cell_image_height = cell_image.size image_x = start_coordinate_x + (cell_width - cell_image_width) // 2 image_y = start_coordinate_y + (row_height - cell_image_height) // 2 image.paste(cell_image, (image_x, image_y), cell_image)
def add_thermometer_icon(image, draw, font, rain_probability, cell_width, row_height, start_coordinate_x, start_coordinate_y): cell_image = Image.open("general_icons/thermometer.png").convert("RGBA") # Изменение размеров иконки термометра cell_image.thumbnail((35, 35)) cell_image_width, cell_image_height = cell_image.size
text_bbox = font.getbbox(rain_probability) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] + text_bbox[1] # Определяем координаты верхнего левого угла для выравнивания картинки и текста image_x = start_coordinate_x + (cell_width - cell_image_width - text_width - 5) // 2 # Учтен отступ в 5 пикселей image_y = start_coordinate_y + (row_height - cell_image_height) // 2 text_x = image_x + cell_image_width + 5 text_y = start_coordinate_y + (row_height - text_height) // 2 image.paste(cell_image, (image_x, image_y), cell_image) draw.text((text_x, text_y), rain_probability, fill=(255, 255, 255), font=font)def add_drops_icon(image, draw, font, rain_probability, cell_width, row_height, start_coordinate_x, start_coordinate_y): cell_image = Image.open("general_icons/drops.png").convert("RGBA") # Изменение размеров иконки термометра cell_image.thumbnail((35, 35)) cell_image_width, cell_image_height = cell_image.size
text_bbox = font.getbbox(rain_probability) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] + text_bbox[1] # Определяем координаты верхнего левого угла для выравнивания картинки и текста image_x = start_coordinate_x + (cell_width - cell_image_width - text_width - 10) // 2 # Учтен отступ в 5 пикселей image_y = start_coordinate_y + (row_height - cell_image_height) // 2 text_x = image_x + cell_image_width + 10 text_y = start_coordinate_y + (row_height - text_height) // 2 image.paste(cell_image, (image_x, image_y), cell_image) draw.text((text_x, text_y), rain_probability, fill=(255, 255, 255), font=font)def add_clock_icon(image, draw, font, rain_probability, cell_width, row_height, start_coordinate_x, start_coordinate_y): cell_image = Image.open("general_icons/clock.png").convert("RGBA") # Изменение размеров иконки термометра cell_image.thumbnail((30, 30)) cell_image_width, cell_image_height = cell_image.size
text_bbox = font.getbbox(rain_probability) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] + text_bbox[1] # Определяем координаты верхнего левого угла для выравнивания картинки и текста image_x = start_coordinate_x + (cell_width - cell_image_width - text_width - 10) // 2 # Учтен отступ в 5 пикселей image_y = start_coordinate_y + (row_height - cell_image_height) // 2 text_x = image_x + cell_image_width + 10 text_y = start_coordinate_y + (row_height - text_height) // 2 image.paste(cell_image, (image_x, image_y), cell_image) draw.text((text_x, text_y), rain_probability, fill=(255, 255, 255), font=font)def get_grandprix_schedule(): y = requests.get("http://ergast.com/api/f1/current.json").json() grandprixs = y["MRData"]["RaceTable"]["Races"] return grandprixs
def eu_time_to_moscow(input_date): date_time_obj = datetime.datetime.strptime(input_date, "%Y-%m-%d %H:%M:%S") moscow_time = format_datetime(date_time_obj, "Y-MM-d H:mm:ss", tzinfo=get_timezone(pytz.timezone('Etc/GMT-3')), locale='ru_RU') return moscow_time
def format_date(input_date): # Преобразование строки в объект datetime date_time_obj = datetime.datetime.strptime(input_date, "%Y-%m-%d %H:%M:%S") formatted_date = format_datetime(date_time_obj, "EEEE, d MMMM", tzinfo=get_timezone(pytz.timezone('Etc/GMT-3')), locale='ru_RU').capitalize() formatted_time = format_datetime(date_time_obj, "HH:mm", tzinfo=get_timezone(pytz.timezone('Etc/GMT-3')), locale='ru_RU')
return formatted_date, formatted_timedef draw_text(draw, font, text, cell_width, row_height, start_coordinate_x, start_coordinate_y): # Делим текст на строки lines = textwrap.wrap(text, width=max(12, 1)) if len(lines) == 1: #Находим размер текста с помощью метода font.getbbox text_bbox = font.getbbox(text) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] + text_bbox[1]
text_x = start_coordinate_x + (cell_width - text_width) // 2 text_y = start_coordinate_y + (row_height - text_height) // 2 draw.text((text_x, text_y), text, fill=(255, 255, 255), font=font) else: max_width = 0 general_height = 0 line_spacing = 5 for word in lines: word_bbox = font.getbbox(word) word_width = word_bbox[2] - word_bbox[0] word_height = word_bbox[3] general_height += word_height if word_width > max_width: max_width = word_width text_x = start_coordinate_x + (cell_width - max_width) // 2 general_height = general_height + (line_spacing * (len(lines) - 1)) text_y = start_coordinate_y + (row_height - general_height) // 2 draw.text((text_x, text_y), text, fill=(255, 255, 255), font=font, spacing=line_spacing, align="center")def draw_run_information(image, draw, font, run, column_widths, column_spacing, row_height, start_coordinate_x, start_coordinate_y): TINT_COLOR = (0, 0, 0) # Black TRANSPARENCY = 0.3 # Degree of transparency, 0-100% OPACITY = int(255 * TRANSPARENCY) overlay = Image.new('RGBA', image.size, TINT_COLOR+(0,))
draw_overlay = ImageDraw.Draw(overlay) # Create a context for drawing things on it. original_image = image for col in range(5): cell_width = column_widths[col] # Рисуем ячейку draw_overlay.rectangle([(start_coordinate_x, start_coordinate_y), (start_coordinate_x + cell_width, start_coordinate_y + row_height)], outline=(255, 165, 0, 72), fill=TINT_COLOR+(OPACITY,)) if col == 0: # Для первого столбца add_weather_icon(overlay, run["run_weathercode"], cell_width, row_height, start_coordinate_x, start_coordinate_y) elif col == 1: draw_text(draw_overlay, font, run["run_name"], cell_width, row_height, start_coordinate_x, start_coordinate_y) elif col == 2: add_thermometer_icon(overlay, draw_overlay, font, run["run_temperature"], cell_width, row_height, start_coordinate_x, start_coordinate_y) elif col == 3: add_drops_icon(overlay, draw_overlay, font, run["run_rain_probability"], cell_width, row_height, start_coordinate_x, start_coordinate_y) elif col == 4: add_clock_icon(overlay, draw_overlay, font, run["run_time"], cell_width, row_height, start_coordinate_x, start_coordinate_y) start_coordinate_x += cell_width + column_spacing # переходим к следующей ячейке # Alpha composite these two images together to obtain the desired result. original_image = Image.alpha_composite(original_image, overlay) image = original_image return imagedef draw_table_with_dates(runs): # Открываем изображение фона background = Image.open("background.png") image_width, image_height = background.size
# Создаем изображение размером 1080x1350 пикселей image = Image.new("RGBA", (1080, 1350), (255, 255, 255)) image.paste(background, (0, 0)) draw = ImageDraw.Draw(image) # Задаем параметры таблицы row_height = 75 column_widths = [75, 305, 125, 125, 150] column_spacing = 10 row_spacing = 10 run_data_font = ImageFont.truetype("RunDataFont.ttf", size=25) date_header_font = ImageFont.truetype("DateHeaderFont.ttf", size=35) image = add_track_image(image) # Вычисляем положение таблицы table_width = sum(column_widths) + column_spacing * (len(column_widths) - 1) table_height = row_height * 5 x = 135 y = 150 #500 current_table_row = 0 current_run = 0 active_run_flag = 0 # Рисуем таблицу for row in range(8): if current_table_row == 0: image = draw_date_header(image, runs[current_run]["run_date"], date_header_font, row_height, x, y) elif current_table_row == 1: image = draw_run_information(image, draw, run_data_font, runs[current_run], column_widths, column_spacing, row_height, x, y) current_run += 1 elif current_table_row >= 2: if runs[current_run]["run_date"] != runs[current_run - 1]["run_date"] and active_run_flag == 0: image = draw_date_header(image, runs[current_run]['run_date'], date_header_font, row_height, x, y) active_run_flag = 1 else: image = draw_run_information(image, draw, run_data_font, runs[current_run], column_widths, column_spacing, row_height, x, y) current_run += 1 active_run_flag = 0 # Переходим на новую строку x = (image.width - table_width) // 2 y += row_height + row_spacing current_table_row += 1 # Сохраняем изображение в файл image.save("table_with_dates.png")def add_track_image(image): track_image = Image.open("tracks/silverstone.png").convert("RGBA") # Открываем картинку “vegas.png”
# Уменьшаем картинку в 2 раза track_image = track_image.resize((track_image.width // 2, track_image.height // 2)) ## Выравниваем картинку по ширине table_width, _ = image.size track_width, track_height = track_image.size x = (table_width - track_width) // 2 # координата Х, чтобы разместить картинку по центру по горизонтали # Стартовая координата по высоте y = 850 # Добавляем картинку на изображение с таблицей image.paste(track_image, (x, y), track_image) return imageПример использования функции с примером словаря данных
runs = [ {"run_name": "Практика 1", "run_date": "Пятница, 21 июля", "run_time": "13:00", "run_temperature": "25°C", "run_rain_probability": "30%", "run_weathercode": "weather_icons/1000.png"}, {"run_name": "Квалификация к гонке", "run_date": "Пятница, 21 июля", "run_time": "16:00", "run_temperature": "26°C", "run_rain_probability": "35%", "run_weathercode": "weather_icons/1001.png"}, {"run_name": '''Квалификация к спринту''', "run_date": "Суббота, 22 июля", "run_time": "13:00", "run_temperature": "27°C", "run_rain_probability": "40%", "run_weathercode": "weather_icons/1100.png"}, {"run_name": "Спринт", "run_date": "Суббота, 22 июля", "run_time": "17:00", "run_temperature": "28°C", "run_rain_probability": "50%", "run_weathercode": "weather_icons/1101.png"}, {"run_name": "Гонка", "run_date": "Воскресенье, 23 июля", "run_time": "18:00", "run_temperature": "29°C", "run_rain_probability": "60%", "run_weathercode": "weather_icons/1102.png"} ] Напиши функцию, которая бы добавляла текст "Гран-При Эмилии-Романьи" и флаг из файла flag.png на оригинальное изображение с таблицей. Текст и флаг должны иметь небольшой отступ друг от друга, быть выровнены по ширине оригинального изображения, а также иметь стартовую координату по вертикали 150.
- Assistant
Функция, которая добавляет текст "Гран-При Эмилии-Романьи" и флаг на оригинальное изображение с таблицей, может выглядеть следующим образом:
from PIL import ImageDraw, ImageFont def add_text_and_flag(image): flag_image = Image.open("flag.png").convert("RGBA") # Открываем изображение флага # Уменьшаем изображение флага до определенного размера flag_image.thumbnail((100, 100)) # Находим размеры изображения image_width, image_height = image.size # Задаем размеры и стиль шрифта для текста text_font = ImageFont.truetype("TextFont.ttf", size=40) # Задаем текст и задаем координаты текста text = "Гран-При Эмилии-Романьи" text_width, text_height = text_font.getsize(text) text_x = (image_width - text_width) // 2 text_y = 100 # Выравниваем изображения по г