| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- """
- Make logo.png background transparent (vectorized, fast).
- Writes to logo.png.tmp then replaces — avoids corrupting the file on failure.
- Tune WHITE_* if edges of the logo are eaten or background remains.
- """
- from __future__ import annotations
- import os
- import numpy as np
- from PIL import Image
- PATH = r"D:\worksspace\s202226701051\word-app\src\assets\icon\logo.png"
- TMP = PATH + ".tmp.png"
- # Pixels matching "light background" become transparent
- WHITE_MIN = 236 # channel minimum for near-white
- WHITE_AVG = 242 # average RGB
- WHITE_SPREAD = 28 # max(r,g,b)-min(r,g,b); logo colors usually higher spread
- def main() -> None:
- im = Image.open(PATH).convert("RGB")
- rgb = np.array(im)
- r = rgb[:, :, 0].astype(np.int16)
- g = rgb[:, :, 1].astype(np.int16)
- b = rgb[:, :, 2].astype(np.int16)
- avg = (r + g + b) / 3
- spread = np.maximum(np.maximum(r, g), b) - np.minimum(np.minimum(r, g), b)
- near_white = (
- (r >= WHITE_MIN) & (g >= WHITE_MIN) & (b >= WHITE_MIN)
- ) | ((avg >= WHITE_AVG) & (spread <= WHITE_SPREAD))
- rgba = np.zeros((rgb.shape[0], rgb.shape[1], 4), dtype=np.uint8)
- rgba[:, :, :3] = rgb
- rgba[:, :, 3] = np.where(near_white, 0, 255).astype(np.uint8)
- out = Image.fromarray(rgba, "RGBA")
- out.save(TMP, "PNG", optimize=True)
- Image.open(TMP).load()
- os.replace(TMP, PATH)
- print("OK:", PATH, "transparent count:", int(near_white.sum()))
- if __name__ == "__main__":
- main()
|