import math import os from PIL import Image, ImageDraw, ImageFont def add_watermark(image, watermark_text, font_path, font_size, opacity, color, right_margin, bottom_margin): # Load the custom font font = ImageFont.truetype(font_path, font_size) # Create a drawing context draw = ImageDraw.Draw(image) # Get the image dimensions image_width, image_height = image.size # Calculate the position for the watermark text_bbox = draw.textbbox((0, 0), watermark_text, font=font) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] - text_bbox[1] + math.floor(font_size / 2) x = image_width - text_width - int(image_width * right_margin) y = image_height - text_height - int(image_height * bottom_margin) # Добавляем отступ снизу # Create a new image for the watermark with alpha channel watermark = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0)) watermark_draw = ImageDraw.Draw(watermark) # Convert the color tuple to a hexadecimal color string hex_color = "#%02x%02x%02x" % color print(color, hex_color) # Draw the watermark text on the new image watermark_draw.text((0, 0), watermark_text, font=font, fill=color + (int(255 * opacity),)) # Paste the watermark onto the original image image.paste(watermark, (x, y), mask=watermark) def process_image(image_path, output_dir, watermark_text=None, font_path=None, font_size=30, opacity=0.5, color="#000000", right_margin=0.05, bottom_margin=0.02): # Convert the color string to a tuple color_tuple = tuple(int(color.lstrip('#')[i:i+2], 16) for i in (0, 2, 4)) # Create output folder os.makedirs(output_dir, exist_ok=True) # Открываем исходное изображение with Image.open(image_path) as img: # Конвертируем изображение в режим RGBA, если необходимо if img.mode != 'RGBA': img = img.convert('RGBA') # Добавляем водяной знак на исходное изображение, если указан текст if watermark_text and font_path: add_watermark(img, watermark_text, font_path, font_size, opacity, color_tuple, right_margin, bottom_margin) # Сохраняем исходное изображение с водяным знаком watermarked_file = os.path.join(output_dir, 'watermarked.png') img.save(watermarked_file, format='PNG') # Создаем миниатюру изображения thumbnail_size = (200, 200) # Укажите нужный размер миниатюры img.thumbnail(thumbnail_size) # Сохраняем миниатюру thumbnail_file = os.path.join(output_dir, 'thumbnail.png') img.save(thumbnail_file, format='PNG') # Возвращаем список с путями к полученным файлам return [watermarked_file, thumbnail_file]