130 lines
4.8 KiB
Python
130 lines
4.8 KiB
Python
from PIL import Image, ImageDraw, ImageFont
|
||
import requests
|
||
from io import BytesIO
|
||
|
||
|
||
methods = {
|
||
'NEAREST': Image.NEAREST,
|
||
'BILINEAR': Image.BILINEAR,
|
||
'BICUBIC': Image.BICUBIC,
|
||
'LANCZOS': Image.LANCZOS,
|
||
'HAMMING': Image.HAMMING,
|
||
'BOX': Image.BOX
|
||
}
|
||
# Скачаем тестовое изображение (или используем свое)
|
||
try:
|
||
# Используем тестовое изображение из интернета
|
||
url = "https://raw.githubusercontent.com/python-pillow/Pillow/main/Tests/images/hopper.jpg"
|
||
response = requests.get(url)
|
||
real_image = Image.open(BytesIO(response.content))
|
||
except:
|
||
pass
|
||
# Или создадим свое
|
||
#real_image = create_test_image()
|
||
|
||
# Уменьшим большое фото и посмотрим разницу
|
||
print(f"Оригинальный размер фото: {real_image.size}")
|
||
|
||
# Уменьшим до 100x100 разными методами
|
||
small_images = {}
|
||
for method_name, method in methods.items():
|
||
small_images[method_name] = real_image.resize((100, 100), resample=method)
|
||
|
||
# Увеличим обратно до 400x400
|
||
enlarged_images = {}
|
||
for method_name, small_img in small_images.items():
|
||
method = methods[method_name]
|
||
enlarged_images[method_name] = small_img.resize((400, 400), resample=method)
|
||
|
||
# Создаем сравнение фрагментов
|
||
print("\nСоздаем увеличенные фрагменты для детального сравнения...")
|
||
|
||
# Выбираем интересную область
|
||
crop_area = (100, 100, 300, 300) # x1, y1, x2, y2
|
||
crops = {}
|
||
for method_name, img in enlarged_images.items():
|
||
crops[method_name] = img.crop(crop_area)
|
||
|
||
# Создаем коллаж из кропов
|
||
crop_collage = Image.new('RGB', (600, 400), color='lightgray')
|
||
draw = ImageDraw.Draw(crop_collage)
|
||
|
||
# Добавляем кропы
|
||
positions = [(0, 0), (200, 0), (400, 0), (0, 200), (200, 200), (400, 200)]
|
||
method_list = list(crops.keys())
|
||
|
||
for i, method_name in enumerate(method_list[:6]): # первые 6 методов
|
||
if i < len(positions):
|
||
crop_img = crops[method_name]
|
||
x, y = positions[i]
|
||
crop_collage.paste(crop_img, (x, y))
|
||
draw.text((x + 5, y + 5), method_name, fill='white')
|
||
|
||
crop_collage.save("crop_comparison.jpg")
|
||
print("Фрагменты сохранены как 'crop_comparison.jpg'")
|
||
|
||
# Покажем разницу в тексте
|
||
print("\n" + "="*60)
|
||
print("СРАВНЕНИЕ НА ТЕКСТЕ:")
|
||
print("="*60)
|
||
|
||
# Создаем изображение с тонким текстом
|
||
text_image = Image.new('RGB', (400, 200), color='white')
|
||
draw = ImageDraw.Draw(text_image)
|
||
|
||
# Мелкий текст
|
||
for i in range(10):
|
||
draw.text((10, 10 + i*18), "The quick brown fox jumps over the lazy dog",
|
||
fill='black', font=ImageFont.load_default())
|
||
|
||
# Ресайзим
|
||
text_methods = {}
|
||
for method_name, method in [('NEAREST', Image.NEAREST),
|
||
('BILINEAR', Image.BILINEAR),
|
||
('LANCZOS', Image.LANCZOS)]:
|
||
# Уменьшаем в 4 раза
|
||
small_text = text_image.resize((100, 50), resample=method)
|
||
# Увеличиваем обратно
|
||
text_methods[method_name] = small_text.resize((400, 200), resample=method)
|
||
|
||
# Сохраняем сравнение текста
|
||
text_collage = Image.new('RGB', (1200, 200), color='white')
|
||
text_collage.paste(text_image, (0, 0))
|
||
draw = ImageDraw.Draw(text_collage)
|
||
draw.text((10, 10), "Оригинал", fill='black')
|
||
|
||
x_offset = 400
|
||
for method_name, img in text_methods.items():
|
||
text_collage.paste(img, (x_offset, 0))
|
||
draw.text((x_offset + 10, 10), method_name, fill='black')
|
||
x_offset += 400
|
||
|
||
text_collage.save("text_comparison.jpg")
|
||
print("Сравнение текста сохранено как 'text_comparison.jpg'")
|
||
|
||
# Финальный вывод
|
||
print("\n" + "="*60)
|
||
print("РЕКОМЕНДАЦИИ:")
|
||
print("="*60)
|
||
print("""
|
||
1. Для ФОТОГРАФИЙ и естественных изображений:
|
||
- LANCZOS - лучшее качество, но медленнее
|
||
- BICUBIC - отличный баланс
|
||
- BILINEAR - если нужна скорость
|
||
|
||
2. Для ТЕКСТА и графики с четкими границами:
|
||
- LANCZOS - сохраняет четкость
|
||
- BICUBIC - хороший вариант
|
||
- Избегайте NEAREST (кроме пиксельной графики)
|
||
|
||
3. Для ПИКСЕЛЬНОЙ ГРАФИКИ (спрайты, ретрографика):
|
||
- NEAREST - сохраняет пиксельный вид
|
||
- Все остальные методы будут размывать
|
||
|
||
4. Для УМЕНЬШЕНИЯ (downscaling):
|
||
- LANCZOS или BICUBIC
|
||
|
||
5. Для УВЕЛИЧЕНИЯ (upscaling):
|
||
- BILINEAR или BOX
|
||
- NEAREST если нужна пиксельность
|
||
""") |