|
| 1 | +import os |
| 2 | +import json |
| 3 | +from PIL import Image |
| 4 | +Image.MAX_IMAGE_PIXELS = None |
| 5 | + |
| 6 | +# Define the base directory |
| 7 | +base_dir = './games/' |
| 8 | + |
| 9 | +def process_directory(directory): |
| 10 | + for root, dirs, files in os.walk(directory): |
| 11 | + if 'config.json' in files: |
| 12 | + config_path = os.path.join(root, 'config.json') |
| 13 | + |
| 14 | + # Skip updating config.json if it is directly in the base_files directory |
| 15 | + if 'base_files' in root and root.count(os.sep) == base_dir.count(os.sep) + 1: |
| 16 | + continue |
| 17 | + |
| 18 | + # Initialize variables to calculate average dimensions |
| 19 | + total_width = 0 |
| 20 | + total_height = 0 |
| 21 | + image_count = 0 |
| 22 | + |
| 23 | + # Loop through files to find image files (including .webp) |
| 24 | + for file in files: |
| 25 | + if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp')): |
| 26 | + image_path = os.path.join(root, file) |
| 27 | + try: |
| 28 | + with Image.open(image_path) as img: |
| 29 | + width, height = img.size |
| 30 | + total_width += width |
| 31 | + total_height += height |
| 32 | + image_count += 1 |
| 33 | + except Exception as e: |
| 34 | + print(f"Error processing image {image_path}: {e}") |
| 35 | + |
| 36 | + # Calculate the average size if images were found |
| 37 | + if image_count > 0: |
| 38 | + average_width = total_width // image_count |
| 39 | + average_height = total_height // image_count |
| 40 | + average_size = {"x": average_width, "y": average_height} |
| 41 | + |
| 42 | + # Read and update the config.json file |
| 43 | + with open(config_path, 'r+', encoding='utf-8') as config_file: |
| 44 | + config_data = json.load(config_file) |
| 45 | + config_data['average_size'] = average_size |
| 46 | + |
| 47 | + # Write the updated data back to config.json |
| 48 | + config_file.seek(0) |
| 49 | + json.dump(config_data, config_file, indent=4) |
| 50 | + config_file.truncate() |
| 51 | + |
| 52 | + print(f"Updated {config_path} with average size: {average_size}") |
| 53 | + else: |
| 54 | + print(f"No images found in {root}") |
| 55 | + |
| 56 | + # If the directory contains "base_files", process its subdirectories |
| 57 | + if 'base_files' in root: |
| 58 | + for sub_dir in dirs: |
| 59 | + process_directory(os.path.join(root, sub_dir)) |
| 60 | + |
| 61 | +# Start processing from the base directory |
| 62 | +process_directory(base_dir) |
0 commit comments