"""把后台维护的天体图标渲染成 ESP32 直接可贴的 RGB565 裸点阵。 终端不解码图片、也不做 alpha:固件用"叠加混合"把不带 alpha 的 RGB565 贴到帧缓冲上, 黑色加上去等于没画,霓虹线稿自动发光。这和 terminal/tools/gen_assets.py 的内置图标 是同一套约定,所以这里必须和它保持同一条流水线: 亮度 bbox 裁切 -> 补方 -> LANCZOS 缩放 -> 黑底门限 -> RGB565(大端)。 改这里记得同步改 gen_assets.py 的 icon_pixels()。 """ from array import array from pathlib import Path from typing import Optional from PIL import Image #: 与 backend/app/main.py 挂载 /upload 的目录一致(相对 backend/ 上传的 file_path 落在这里) UPLOAD_ROOT = (Path(__file__).resolve().parent.parent.parent / "upload").resolve() BBOX_LUMA = 40 # 亮度高于它的算"有墨",用来裁掉四周留白 BLACK_FLOOR = 10 # 亮度不高于它的直接归零,叠加混合时不落地 def icon_file(file_path: str) -> Optional[Path]: """resources.file_path(形如 icon/xxx.jpeg)-> 磁盘绝对路径,越界或不存在返回 None""" root = UPLOAD_ROOT candidate = (root / file_path).resolve() if root not in candidate.parents or not candidate.is_file(): return None return candidate def render_rgb565(path: Path, size: int) -> bytes: """任意位图 -> size x size 的 RGB565 大端裸数据(size*size*2 字节)""" with Image.open(path) as src: ink = src.convert("L").point(lambda v: 255 if v > BBOX_LUMA else 0) im = src.convert("RGB") bbox = ink.getbbox() if bbox: im = im.crop(bbox) w, h = im.size side = max(w, h) square = Image.new("RGB", (side, side), (0, 0, 0)) square.paste(im, ((side - w) // 2, (side - h) // 2)) square = square.resize((size, size), Image.LANCZOS) out = array("H") for r, g, b in square.getdata(): if (r * 299 + g * 587 + b * 114) // 1000 <= BLACK_FLOOR: out.append(0) else: out.append(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)) out.byteswap() # 帧缓冲按大端存放 return out.tobytes()