📄 png_to_svg.py (thème : theme_elmo_materiaux)

import os
from PIL import Image
import numpy as np
import subprocess
import sys
from os.path import join as opj


def png_to_svg(png_path, svg_path):
    if not os.path.exists(png_path):
        raise FileNotFoundError(f"Image introuvable : {png_path}")

    # Préparation du chemin temporaire
    pbm_path = png_path.replace(".png", ".pbm")

    # Convertir PNG en noir et blanc (1-bit)
    image = Image.open(png_path).convert("L")
    bw = image.point(lambda x: 0 if x < 128 else 255, '1')

    # Sauvegarde manuelle en PBM (ASCII)
    width, height = bw.size
    pixels = list(bw.getdata())
    pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]

    with open(pbm_path, 'w') as f:
        f.write("P1\n")
        f.write(f"{width} {height}\n")
        for row in pixels:
            f.write(" ".join(['1' if pixel == 0 else '0' for pixel in row]) + "\n")

    # Conversion en SVG avec potrace
    subprocess.run(["potrace", pbm_path, "-s", "-o", svg_path], check=True)

    # Nettoyage du .pbm temporaire
    os.remove(pbm_path)

    print(f"✅ Conversion terminée : {svg_path}")

# Exemple d'utilisation
if __name__ == "__main__":
    _path = "/opt/odoo/common-addons_v16/theme_elmo_materiaux/"
    if len(sys.argv) > 1:
        image = sys.argv[1]
        if image.startswith('./'):
            image = image.replace('./','')
        png_input = opj(_path, image)
        print("png_input : %s"%(png_input,))
        image_dir = os.path.dirname(image)
        svg_output = opj(_path, image_dir, os.path.basename(image)) 
        svg_output, ext = os.path.splitext(svg_output) 
        svg_output += '.svg'
        print("svg_output : %s"%(svg_output,))
        png_to_svg(png_input, svg_output)

← Revenir à la galerie