Added Multiprocessing to OptimizeTextures

This commit is contained in:
Killergnom
2024-11-18 23:18:52 +01:00
parent 8f22b28e0c
commit 06b5edf33f
11 changed files with 249 additions and 174 deletions

View File

@@ -1,35 +1,65 @@
from unittest import skip
from PIL import Image
import sys
import os
import time
from multiprocessing import Pool, cpu_count, freeze_support
if len(sys.argv) < 1:
print("Please provide the input files.")
sys.exit(1)
inputTexs = sys.argv
if not os.path.exists(os.path.join(os.path.dirname(inputTexs[1]),"optimized")):
os.mkdir(os.path.join(os.path.dirname(inputTexs[1]),"optimized"))
export_path = os.path.join(os.path.dirname(inputTexs[1]),"optimized")
print("Starting optimization of " + str(len(inputTexs)-1) + " Files")
for i in range(1,len(inputTexs),1):
currentTex = Image.open(inputTexs[i])
if currentTex.size <= (2048,2048):
print (f"{os.path.basename(inputTexs[i])} is already smaller than 2048x2048")
continue
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 an LANCZOS filter (gives the highest quality)
resizedTex = currentTex.resize((2048,2048),Image.LANCZOS)
resizedTex.save(str(export_path) + "\\" + os.path.basename(inputTexs[i]), optimize=True, quality=95)
print (os.path.basename(inputTexs[i]) + " successfully converted " + "(" + str(i) + "/" + str(len(inputTexs)-1) + ")")
# 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}")
print("Textures successfully resized!")
time.sleep(5)
def main():
if len(sys.argv) < 2:
print("Please provide the input files.")
sys.exit(1)
inputTexs = sys.argv[1:]
export_dir = os.path.join(os.path.dirname(inputTexs[0]), "optimized")
if not os.path.exists(export_dir):
os.mkdir(export_dir)
total_files = len(inputTexs)
print(f"Starting optimization of {total_files} files")
# 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
print(f"Textures successfully resized in {elapsed_time:.2f} seconds!")
time.sleep(5)
if __name__ == "__main__":
freeze_support()
main()