Advertisement
Guest User

Создание коллажа

a guest
Jan 25th, 2025
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.73 KB | Photo | 0 0
  1. from PIL import Image, ImageFile
  2. import os
  3.  
  4. # Включаем загрузку обрезанных изображений
  5. ImageFile.LOAD_TRUNCATED_IMAGES = True
  6. ALLOWED_EXTENSIONS = '.png', '.jpg', '.jpeg', '.bmp', '.gif'
  7.  
  8. def create_collage(image_folder, output_path, max_width, max_height, target_height):
  9.     # Получаем список всех изображений в папке
  10.     image_paths = [os.path.join(image_folder, f) for f in os.listdir(image_folder)
  11.                    if f.lower().endswith((ALLOWED_EXTENSIONS))]
  12.    
  13.     if not image_paths:
  14.         print("В папке нет изображений!")
  15.         return
  16.    
  17.     images = []
  18.    
  19.     # Загружаем изображения и изменяем их размер
  20.     for img_path in image_paths:
  21.         try:
  22.             img = Image.open(img_path)
  23.             # Вычисляем новый размер, сохраняя пропорции
  24.             width_percent = (target_height / float(img.size[1]))
  25.             new_width = int((float(img.size[0]) * float(width_percent)))
  26.             img = img.resize((new_width, target_height), Image.LANCZOS)
  27.             images.append(img)
  28.         except Exception as e:
  29.             print(f"Ошибка при обработке изображения {img_path}: {e}")
  30.    
  31.     collage_number = 1
  32.     while images:
  33.         # Создаем новый холст
  34.         collage = Image.new('RGB', (max_width, max_height), (255, 255, 255))  # Белый фон
  35.         x_offset, y_offset = 0, 0
  36.         row_height = target_height
  37.         remaining_images = []
  38.  
  39.         for img in images:
  40.             # Если изображение не помещается в текущий ряд, переходим на следующий ряд
  41.             if x_offset + img.width > max_width:
  42.                 x_offset = 0
  43.                 y_offset += row_height
  44.                 row_height = img.height  # Высота нового ряда
  45.            
  46.             # Если новый ряд не помещается на холст, сохраняем изображение для следующего коллажа
  47.             if y_offset + row_height > max_height:
  48.                 remaining_images.append(img)
  49.                 continue
  50.            
  51.             # Вставляем изображение на холст
  52.             collage.paste(img, (x_offset, y_offset))
  53.             x_offset += img.width
  54.        
  55.         # Обрезаем пустое место внизу
  56.         if y_offset + row_height < max_height:
  57.             collage = collage.crop((0, 0, max_width, y_offset + row_height))
  58.        
  59.         # Сохраняем коллаж
  60.         if collage_number == 1:
  61.             collage_output_path = output_path
  62.         else:
  63.             name, ext = os.path.splitext(output_path)
  64.             collage_output_path = f"{name}_{collage_number}{ext}"
  65.        
  66.         collage.save(collage_output_path)
  67.         print(f"Коллаж сохранен в {collage_output_path}")
  68.        
  69.         # Если остались изображения, создаем новый коллаж
  70.         if remaining_images:
  71.             images = remaining_images
  72.             collage_number += 1
  73.         else:
  74.             break
  75.  
  76. # Настройки
  77. image_folder = './images'   # Папка с изображениями
  78. output_path = 'collage.jpg' # Название выходного файла
  79. max_width = 6000            # Ширина коллажа
  80. max_height = 6000           # Высота коллажа
  81. target_height = 300         # Высота картинки в коллаже
  82.  
  83. # Создаём коллаж
  84. create_collage(image_folder, output_path, max_width, max_height, target_height)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement