Created
August 20, 2023 22:26
-
-
Save PaulloClara/29d465633f7232c8ed225e771fddb083 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from PIL import Image | |
def convert_images_to_webp(input_dir, output_dir): | |
# Verifica se o diretório de saída existe, se não, cria-o | |
if not os.path.exists(output_dir): | |
os.makedirs(output_dir) | |
# Lista todos os arquivos no diretório de entrada | |
image_files = os.listdir(input_dir) | |
# Loop através de cada arquivo no diretório de entrada | |
for file_name in image_files: | |
if file_name.lower().endswith(('.png', '.jpg', '.jpeg')): | |
input_path = os.path.join(input_dir, file_name) | |
output_path = os.path.join(output_dir, os.path.splitext(file_name)[0] + '.webp') | |
# Abre a imagem usando a biblioteca Pillow | |
img = Image.open(input_path) | |
# Redimensiona a imagem se a largura for maior que 640 pixels | |
if img.width > 640: | |
aspect_ratio = img.width / img.height | |
new_width = 640 | |
new_height = int(new_width / aspect_ratio) | |
img = img.resize((new_width, new_height), Image.LANCZOS) | |
# Converte e salva a imagem no formato WebP | |
img.save(output_path, 'webp', quality=90) | |
print(f'Conversão de {input_path} para {output_path} concluída.') | |
# Diretório de entrada das imagens | |
input_directory = 'caminha/imagens/entrada' | |
# Diretório de saída das imagens convertidas | |
output_directory = 'caminho/imagens/saida' | |
convert_images_to_webp(input_directory, output_directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment