Aquí tienes un script en Python que realiza todas las tareas que has descrito:
import os
import sys
import datetime
from PIL import Image
import zipfile
def process_image(image_path, my_image_width):
with Image.open(image_path) as img:
# Calcular el recorte centrado
width, height = img.size
min_dim = min(width, height)
crop_dim = min(min_dim, my_image_width)
left = (width - crop_dim) // 2
top = (height - crop_dim) // 2
right = (width + crop_dim) // 2
bottom = (height + crop_dim) // 2
img_cropped = img.crop((left, top, right, bottom))
img_cropped = img_cropped.resize((my_image_width, my_image_width), Image.ANTIALIAS)
# Generar nombre para la imagen recortada
base_name, ext = os.path.splitext(os.path.basename(image_path))
new_name = f"{base_name}_crop_{my_image_width}.png"
return img_cropped, new_name
def save_image(img, new_name, output_dir):
output_path = os.path.join(output_dir, new_name)
img.save(output_path)
def process_directory(directory_path, my_image_width, output_dir):
for filename in os.listdir(directory_path):
if filename.lower().endswith('.png'):
image_path = os.path.join(directory_path, filename)
img_cropped, new_name = process_image(image_path, my_image_width)
save_image(img_cropped, new_name, output_dir)
def create_zip_file(output_dir):
zip_filename = f"{output_dir}.zip"
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(output_dir):
for file in files:
zipf.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(output_dir, '..')))
def main():
if len(sys.argv) < 3:
print("Uso: python script.py <ruta_imagen_o_directorio> <my_image_width> [z]")
sys.exit(1)
path = sys.argv[1]
my_image_width = int(sys.argv[2])
# Crear nombre para el directorio de salida
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
output_dir = f"images_{timestamp}"
os.makedirs(output_dir, exist_ok=True)
# Procesar imagen o directorio
if os.path.isfile(path):
img_cropped, new_name = process_image(path, my_image_width)
save_image(img_cropped, new_name, output_dir)
elif os.path.isdir(path):
process_directory(path, my_image_width, output_dir)
else:
print(f"{path} no es un archivo o directorio válido.")
sys.exit(1)
# Crear archivo ZIP si se proporciona el argumento 'z'
if len(sys.argv) == 4 and sys.argv[3] == 'z':
create_zip_file(output_dir)
if __name__ == "__main__":
main()
- Guardar el script: Copia y guarda el código en un archivo Python, por ejemplo
crop_images.py
. - Ejecutar el script desde la línea de comandos:
python crop_images.py <ruta_imagen_o_directorio> <my_image_width> [z]
<ruta_imagen_o_directorio>
: Ruta de la imagen PNG o directorio a procesar.<my_image_width>
: Longitud deseada para el recorte en píxeles.[z]
: Argumento opcional para crear un archivo ZIP.
python crop_images.py mi_imagen.png 1500
Esto procesará la imagen mi_imagen.png
, recortándola y redimensionándola a 1500x1500
píxeles, y guardará el resultado en un nuevo directorio.
python crop_images.py mi_carpeta 2000 z
Esto procesará todas las imágenes PNG dentro de mi_carpeta
, las recortará y redimensionará a 2000x2000
píxeles, y comprimirá las imágenes resultantes en un archivo ZIP.