File size: 3,356 Bytes
3cb99fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import xml.etree.ElementTree as ET
import cairosvg
from pathlib import Path


def batch_render_kanji(xml_file_path, output_dir="kanji_images_rendered", size=256, bg_color="white"):
    """
    Parses a full KanjiVG XML file and renders every kanji to a PNG image
    with a specified background color.

    Args:
        xml_file_path (str or Path): Path to the kanjivg XML file.
        output_dir (str or Path): Directory where the PNG images will be saved.
        size (int): The width and height of the output PNGs in pixels.
        bg_color (str): The background color for the image (e.g., 'white', '#FFFFFF').
                        Set to None for a transparent background.
    """
    output_path = Path(output_dir)
    output_path.mkdir(exist_ok=True)
    print(f"Output directory set to: {output_path.resolve()}")
    if bg_color:
        print(f"Background color set to: '{bg_color}'")
    else:
        print("Background is set to transparent.")

    try:
        print(f"Loading and parsing XML file: {xml_file_path}...")
        tree = ET.parse(xml_file_path)
        root = tree.getroot()
    except ET.ParseError as e:
        print(f"Fatal Error: Could not parse XML file. Details: {e}")
        return
    except FileNotFoundError:
        print(f"Fatal Error: The file was not found at '{xml_file_path}'")
        return

    kanji_elements = root.findall('.//kanji')
    total_kanji = len(kanji_elements)
    print(f"Found {total_kanji} kanji elements to render.")

    if total_kanji == 0:
        print("No kanji elements were found. Please check the XML file content.")
        return

    for i, kanji_element in enumerate(kanji_elements):
        kanji_id = kanji_element.attrib.get('id', f'unknown_{i}')
        hex_codepoint = kanji_id.split('_')[-1]
        
        g_element = kanji_element.find('{http://kanjivg.tagaini.net}g') or kanji_element.find('g')
        
        if g_element is None:
            print(f"[{i+1}/{total_kanji}] Skipping {kanji_id}: No drawable <g> element found.")
            continue

        g_string = ET.tostring(g_element, encoding='unicode')

        svg_document = f'''<?xml version="1.0" encoding="UTF-8"?>
<svg width="{size}px" height="{size}px" viewBox="0 0 109 109" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <g fill="none" stroke="#000000" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
    {g_string}
  </g>
</svg>'''

        output_filename = output_path / f"U+{hex_codepoint}.png"

        try:
            # --- MODIFICATION HERE ---
            # Added the 'background_color' parameter to the rendering function.
            cairosvg.svg2png(
                bytestring=svg_document.encode('utf-8'),
                write_to=str(output_filename),
                background_color=bg_color
            )
            if (i + 1) % 100 == 0 or i == total_kanji - 1:
                 print(f"[{i+1}/{total_kanji}] Successfully rendered: {output_filename.name}")
        except Exception as e:
            print(f"[{i+1}/{total_kanji}] Failed to render {kanji_id}: {e}")

    print("\nBatch rendering complete.")


if __name__ == "__main__":
    image_directory = "kanji_images"
    kanjivg_xml_path = "kanjivg-20220427.xml.xml"
    image_size = 1024 
    bg_color = "white" 

    batch_render_kanji(kanjivg_xml_path, image_directory, image_size, bg_color)