Files
1960-utils/Texturing/OptimizeTextures/optimize_textures.py

65 lines
1.9 KiB
Python
Raw Normal View History

2024-03-18 14:42:50 +01:00
from PIL import Image
import sys
import os
2024-03-23 14:21:12 +01:00
import time
from multiprocessing import Pool, cpu_count, freeze_support
2024-03-18 14:42:50 +01:00
def process_image(args):
input_path, export_dir, idx, total = args
try:
currentTex = Image.open(input_path)
if currentTex.size <= (2048, 2048):
print(f"{os.path.basename(input_path)} is already smaller than 2048x2048 ({idx}/{total})")
return
# Downsize the image with a LANCZOS filter
resizedTex = currentTex.resize((2048, 2048), Image.LANCZOS)
output_path = os.path.join(export_dir, os.path.basename(input_path))
resizedTex.save(output_path, optimize=True, quality=95)
print(f"{os.path.basename(input_path)} successfully converted ({idx}/{total})")
except Exception as e:
print(f"Error processing {input_path} ({idx}/{total}): {e}")
2024-03-18 14:42:50 +01:00
def main():
if len(sys.argv) < 2:
print("Please provide the input files.")
sys.exit(1)
2024-03-18 14:42:50 +01:00
inputTexs = sys.argv[1:]
export_dir = os.path.join(os.path.dirname(inputTexs[0]), "optimized")
2024-03-18 14:42:50 +01:00
if not os.path.exists(export_dir):
os.mkdir(export_dir)
2024-03-18 14:42:50 +01:00
total_files = len(inputTexs)
print(f"Starting optimization of {total_files} files")
2024-03-18 14:42:50 +01:00
# Start timing
start_time = time.perf_counter()
args_list = [
(input_path, export_dir, idx + 1, total_files)
for idx, input_path in enumerate(inputTexs)
]
# Check if running as a frozen executable
if getattr(sys, 'frozen', False):
# Avoid multiprocessing when frozen
for args in args_list:
process_image(args)
else:
with Pool(processes=cpu_count()) as pool:
pool.map(process_image, args_list)
# End timing
end_time = time.perf_counter()
elapsed_time = end_time - start_time
2024-03-18 14:42:50 +01:00
print(f"Textures successfully resized in {elapsed_time:.2f} seconds!")
time.sleep(5)
2024-03-18 14:42:50 +01:00
if __name__ == "__main__":
freeze_support()
main()