|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import subprocess |
| 4 | +from pathlib import Path |
| 5 | +from PIL import Image |
| 6 | +import struct |
| 7 | + |
| 8 | +# Take build directory as argument to save generated C files and PNG files. |
| 9 | +parser = argparse.ArgumentParser(description="Convert SVG files to PNG.") |
| 10 | +parser.add_argument("dest", help="Destination build folder for PNG files.") |
| 11 | +args = parser.parse_args() |
| 12 | + |
| 13 | +build_dir = Path(args.dest) |
| 14 | +build_dir.mkdir(parents=True, exist_ok=True) |
| 15 | +media_dir = Path(__file__).parent / "media" |
| 16 | + |
| 17 | +# Convert all SVG files in media_dir to PNG and save in build_dir if not already present. |
| 18 | +svg_files = media_dir.rglob("*.svg") |
| 19 | +for svg in svg_files: |
| 20 | + png = svg.with_suffix(".png").name |
| 21 | + png_path = build_dir / png |
| 22 | + if png_path.exists(): |
| 23 | + continue |
| 24 | + subprocess.run(["cairosvg", str(svg), "-o", str(png_path)]) |
| 25 | + |
| 26 | +# Collect all image files in media_dir (png, bmp, jpg) and build_dir (png), including subfolders. |
| 27 | +media_images = ( |
| 28 | + list(media_dir.rglob("*.png")) |
| 29 | + + list(media_dir.rglob("*.bmp")) |
| 30 | + + list(media_dir.rglob("*.jpg")) |
| 31 | + + list(build_dir.rglob("*.png")) |
| 32 | +) |
| 33 | + |
| 34 | + |
| 35 | +# Convert rgba to monochrome, treating fully transparent pixels as white. |
| 36 | +def is_black(r, g, b, a): |
| 37 | + if a == 0: |
| 38 | + return 0 |
| 39 | + return 1 if (r + g + b) < (128 * 3) else 0 |
| 40 | + |
| 41 | + |
| 42 | +def image_to_mono_flip_256(img): |
| 43 | + img = img.convert("RGBA") |
| 44 | + pixels = img.load() |
| 45 | + |
| 46 | + # Flatten the image into a single list in raster order |
| 47 | + mono = [is_black(*pixels[x, y]) for y in range(height) for x in range(width)] |
| 48 | + last = 0 |
| 49 | + flips = [] |
| 50 | + |
| 51 | + if width > 256 or height > 256: |
| 52 | + raise ValueError("Image is too large for flip compression.") |
| 53 | + |
| 54 | + for idx in range(width * height): |
| 55 | + if mono[idx] != last: |
| 56 | + flips.append(idx) |
| 57 | + last = mono[idx] |
| 58 | + |
| 59 | + # Pack flip indices into bytes, 2 indices per byte |
| 60 | + return struct.pack(f"<{len(flips)}h", *flips) |
| 61 | + |
| 62 | + |
| 63 | +def image_to_8bit_map(img): |
| 64 | + img = img.convert("RGBA") |
| 65 | + width, height = img.size |
| 66 | + pixels = img.load() |
| 67 | + mono = [is_black(*pixels[x, y]) for y in range(height) for x in range(width)] |
| 68 | + |
| 69 | + # go in chunks of 8 pixels and pack into a byte |
| 70 | + data = [] |
| 71 | + for i in range(0, len(mono), 8): |
| 72 | + byte = 0 |
| 73 | + for j in range(8): |
| 74 | + if i + j < len(mono): |
| 75 | + byte |= mono[i + j] << (7 - j) |
| 76 | + data.append(byte) |
| 77 | + |
| 78 | + return bytes(data) |
| 79 | + |
| 80 | + |
| 81 | +COMPRESSION_TYPES = { |
| 82 | + "PBIO_IMAGE_COMPRESSION_MONOCHROME_8BIT_MAP": image_to_8bit_map, |
| 83 | + "PBIO_IMAGE_COMPRESSION_MONOCHROME_256x256_FLIP": image_to_mono_flip_256, |
| 84 | +} |
| 85 | + |
| 86 | + |
| 87 | +# Get printable C struct for the compressed image data. |
| 88 | +def get_c_const_struct(name, compression_type, width, height, flip_data): |
| 89 | + bytes_per_line = 12 |
| 90 | + lines = [] |
| 91 | + for i in range(0, len(flip_data), bytes_per_line): |
| 92 | + chunk = flip_data[i : i + bytes_per_line] |
| 93 | + line = " " + ", ".join(f"0x{val:02x}" for val in chunk) |
| 94 | + lines.append(line) |
| 95 | + data_literal = ",\n".join(lines) + "," |
| 96 | + |
| 97 | + return f""" |
| 98 | +static const uint8_t {name}_data[] = {{ |
| 99 | +{data_literal} |
| 100 | +}}; |
| 101 | +
|
| 102 | +const pbio_image_compressed_t pbio_image_media_{name} = {{ |
| 103 | + .type = {compression_type}, |
| 104 | + .width = {width}, |
| 105 | + .height = {height}, |
| 106 | + .name = "{name.upper()}", |
| 107 | + .data = {name}_data, |
| 108 | + .data_size = sizeof({name}_data), |
| 109 | +}}; |
| 110 | +""" |
| 111 | + |
| 112 | + |
| 113 | +c_file_contents = """// SPDX-License-Identifier: MIT |
| 114 | +// Copyright (c) 2025 The Pybricks Authors |
| 115 | +
|
| 116 | +#include <pbio/image.h> |
| 117 | +#include <pbio/util.h> |
| 118 | +#include <string.h> |
| 119 | +""" |
| 120 | + |
| 121 | +c_struct_names = [] |
| 122 | + |
| 123 | +h_file_contents = f"{c_file_contents}\n\nextern const pbio_image_compressed_t *pbio_image_media_lookup(const char *name);\n" |
| 124 | + |
| 125 | + |
| 126 | +# Process each image. Compress using both methods and choose the smaller one. |
| 127 | +for img_path in media_images: |
| 128 | + with Image.open(img_path) as img: |
| 129 | + name = Path(img_path.name).stem |
| 130 | + |
| 131 | + width, height = img.size |
| 132 | + |
| 133 | + min_size = width * height |
| 134 | + print(name) |
| 135 | + for compression_type, compression_func in COMPRESSION_TYPES.items(): |
| 136 | + bin_data = compression_func(img) |
| 137 | + print(f" {compression_type}: {len(bin_data)} bytes") |
| 138 | + if len(bin_data) < min_size: |
| 139 | + min_size = len(bin_data) |
| 140 | + best_compression_type = compression_type |
| 141 | + best_bin_data = bin_data |
| 142 | + |
| 143 | + if len(best_bin_data) >= width * height: |
| 144 | + raise ValueError(f"Warning: {name} is not smaller than raw bitmap.") |
| 145 | + |
| 146 | + c_struct_names.append("pbio_image_media_" + name) |
| 147 | + c_file_contents += get_c_const_struct( |
| 148 | + name, best_compression_type, width, height, best_bin_data |
| 149 | + ) |
| 150 | + h_file_contents += ( |
| 151 | + f"\nextern const pbio_image_compressed_t pbio_image_media_{name};\n" |
| 152 | + ) |
| 153 | + |
| 154 | + |
| 155 | +c_file_contents += "\nstatic const pbio_image_compressed_t pbio_image_media_all[] = {\n" |
| 156 | +for struct_name in c_struct_names: |
| 157 | + c_file_contents += f" {struct_name},\n" |
| 158 | +c_file_contents += "};\n" |
| 159 | + |
| 160 | +c_file_contents += """ |
| 161 | +const pbio_image_compressed_t *pbio_image_media_lookup(const char *name) { |
| 162 | + for (size_t i = 0; i < PBIO_ARRAY_SIZE(pbio_image_media_all); i++) { |
| 163 | + if (strncmp(pbio_image_media_all[i].name, name, strlen(pbio_image_media_all[i].name)) == 0) { |
| 164 | + return &pbio_image_media_all[i]; |
| 165 | + } |
| 166 | + } |
| 167 | + return NULL; |
| 168 | +} |
| 169 | +""" |
| 170 | + |
| 171 | +with open(build_dir / "pbio_image_media.c", "w") as c_file: |
| 172 | + c_file.write(c_file_contents) |
| 173 | + |
| 174 | +with open(build_dir / "pbio_image_media.h", "w") as h_file: |
| 175 | + h_file.write(h_file_contents) |
0 commit comments