Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PIL import Image, ImageFile
- import os
- # Включаем загрузку обрезанных изображений
- ImageFile.LOAD_TRUNCATED_IMAGES = True
- ALLOWED_EXTENSIONS = '.png', '.jpg', '.jpeg', '.bmp', '.gif'
- def create_collage(image_folder, output_path, max_width, max_height, target_height):
- # Получаем список всех изображений в папке
- image_paths = [os.path.join(image_folder, f) for f in os.listdir(image_folder)
- if f.lower().endswith((ALLOWED_EXTENSIONS))]
- if not image_paths:
- print("В папке нет изображений!")
- return
- images = []
- # Загружаем изображения и изменяем их размер
- for img_path in image_paths:
- try:
- img = Image.open(img_path)
- # Вычисляем новый размер, сохраняя пропорции
- width_percent = (target_height / float(img.size[1]))
- new_width = int((float(img.size[0]) * float(width_percent)))
- img = img.resize((new_width, target_height), Image.LANCZOS)
- images.append(img)
- except Exception as e:
- print(f"Ошибка при обработке изображения {img_path}: {e}")
- collage_number = 1
- while images:
- # Создаем новый холст
- collage = Image.new('RGB', (max_width, max_height), (255, 255, 255)) # Белый фон
- x_offset, y_offset = 0, 0
- row_height = target_height
- remaining_images = []
- for img in images:
- # Если изображение не помещается в текущий ряд, переходим на следующий ряд
- if x_offset + img.width > max_width:
- x_offset = 0
- y_offset += row_height
- row_height = img.height # Высота нового ряда
- # Если новый ряд не помещается на холст, сохраняем изображение для следующего коллажа
- if y_offset + row_height > max_height:
- remaining_images.append(img)
- continue
- # Вставляем изображение на холст
- collage.paste(img, (x_offset, y_offset))
- x_offset += img.width
- # Обрезаем пустое место внизу
- if y_offset + row_height < max_height:
- collage = collage.crop((0, 0, max_width, y_offset + row_height))
- # Сохраняем коллаж
- if collage_number == 1:
- collage_output_path = output_path
- else:
- name, ext = os.path.splitext(output_path)
- collage_output_path = f"{name}_{collage_number}{ext}"
- collage.save(collage_output_path)
- print(f"Коллаж сохранен в {collage_output_path}")
- # Если остались изображения, создаем новый коллаж
- if remaining_images:
- images = remaining_images
- collage_number += 1
- else:
- break
- # Настройки
- image_folder = './images' # Папка с изображениями
- output_path = 'collage.jpg' # Название выходного файла
- max_width = 6000 # Ширина коллажа
- max_height = 6000 # Высота коллажа
- target_height = 300 # Высота картинки в коллаже
- # Создаём коллаж
- create_collage(image_folder, output_path, max_width, max_height, target_height)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement