PYTHON: a tool to convert AI files to PNG

I wrote this Python script to convert all .ai (Adobe Illustrator) files in a folder to .png.
I needed this because a client sent me hundreds of sprites in .ai and I needed to convert each of them to PNG to import in our Unity project. So here’s how to use it:

How to Run:

  1. Download Python (here) and install it
  2. Download Inkscape (here) and install it on “C:\Program Files”
  3. Open Visual Studio and create a Python file (.py) with the following script:
import os
import glob
import subprocess

def convert_ai_to_png(ai_file_path, output_dir):
    """
    Converts an .ai file to .png using Inkscape command-line.
    Args:
        ai_file_path (str): Path to the .ai file.
        output_dir (str): Directory to save the .png file.
    """
    output_file = os.path.join(output_dir, os.path.basename(ai_file_path).replace(".ai", ".png"))
    # Using Inkscape to convert AI file to PNG
    command = [
        r'C:\\Program Files\\Inkscape\\bin\\inkscape.exe',
        ai_file_path,
        '--export-type=png',
        '--export-filename=' + output_file
    ]
    try:
        subprocess.run(command, check=True)
        print(f"Converted: {ai_file_path} to {output_file}")
    except subprocess.CalledProcessError as e:
        print(f"Error converting {ai_file_path}: {e}")

def convert_all_ai_files_in_directory(directory):
    """
    Scans the directory for .ai files and converts them to .png.
    Args:
        directory (str): Directory path to scan for .ai files.
    """
    # Find all .ai files in the directory
    ai_files = glob.glob(os.path.join(directory, "*.ai"))
    if ai_files:
        output_dir = os.path.join(directory, "converted_pngs")
        os.makedirs(output_dir, exist_ok=True)
        
        for ai_file in ai_files:
            convert_ai_to_png(ai_file, output_dir)
    else:
        print("No .ai files found in the directory.")

if __name__ == "__main__":
    folder = input("Enter the folder path containing .ai files: ")
    if os.path.isdir(folder):
        convert_all_ai_files_in_directory(folder)
    else:
        print("Invalid directory path.")
  1. Run Script (it runs on Terminal)
  2. Enter the image folder path
  3. Wait
  4. Check the converted PNG files inside the folder “converted_pngs” which was created inside
  5. Be happy!

Attention:
This script won’t work if you don’t install Inkscape at “C:\Program Files\Inkscape”. (you can change this path on the 15th line of the script)

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *