1
0

trimmer.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os
  2. from PIL import Image
  3. import sys
  4. def trim_png_transparency(directory):
  5. """
  6. Opens all PNG files in the specified directory, trims transparent borders,
  7. and overwrites the original files.
  8. Args:
  9. directory (str): The path to the directory containing PNG files.
  10. """
  11. if not os.path.isdir(directory):
  12. print(f"Error: Directory not found: {directory}")
  13. return
  14. print(f"Scanning directory: {directory}")
  15. trimmed_count = 0
  16. skipped_count = 0
  17. error_count = 0
  18. for filename in os.listdir(directory):
  19. if filename.lower().endswith(".png"):
  20. file_path = os.path.join(directory, filename)
  21. try:
  22. img = Image.open(file_path)
  23. # Ensure image has an alpha channel
  24. if img.mode != "RGBA":
  25. img = img.convert("RGBA")
  26. # Get the bounding box of the non-transparent area
  27. bbox = img.getbbox()
  28. if bbox:
  29. # Crop the image to the contents of the bounding box
  30. img_cropped = img.crop(bbox)
  31. # Check if cropping actually changed the size
  32. if img_cropped.size != img.size:
  33. # Save the cropped image, overwriting the original
  34. img_cropped.save(file_path)
  35. print(f"Trimmed: {filename}")
  36. trimmed_count += 1
  37. else:
  38. print(f"Skipped (no transparency to trim): {filename}")
  39. skipped_count += 1
  40. else:
  41. # Handle completely transparent images (optional: delete or skip)
  42. print(f"Skipped (image is fully transparent): {filename}")
  43. skipped_count += 1
  44. img.close() # Close the original image handle
  45. except Exception as e:
  46. print(f"Error processing {filename}: {e}")
  47. error_count += 1
  48. print("\n--- Processing Summary ---")
  49. print(f"Trimmed files: {trimmed_count}")
  50. print(f"Skipped files: {skipped_count}")
  51. print(f"Errors: {error_count}")
  52. print("------------------------")
  53. # --- Configuration ---
  54. # IMPORTANT: Replace this with the actual path to your image directory!
  55. image_directory = (
  56. r"d:\GitHub\Civ14\Resources\Textures\Interface\Misc\civ_hud_squads.rsi"
  57. )
  58. # Example: image_directory = r'd:\GitHub\Civ14\Resources\Textures\Interface\Misc'
  59. # --- End Configuration ---
  60. trim_png_transparency(image_directory)