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 element found.") continue g_string = ET.tostring(g_element, encoding='unicode') svg_document = f''' {g_string} ''' 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)