|
| 1 | +"""把 icon.ico 转成 macOS 用的 icon.icns。 |
| 2 | +
|
| 3 | + python macos/make_icns.py |
| 4 | +
|
| 5 | +macOS 上会调用系统自带的 iconutil 生成真正的 .icns。 |
| 6 | +其它系统上只会生成中间的 icon.iconset/ 目录并提示你 —— 因为 .icns 的打包 |
| 7 | +必须靠 iconutil,Windows/Linux 上没有这个工具。 |
| 8 | +没有 .icns 也能打包,只是 Dock 图标会是 PyInstaller 的默认图标。 |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | +import subprocess |
| 13 | +import sys |
| 14 | + |
| 15 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 16 | +SOURCE = os.path.join(ROOT, "icon.ico") |
| 17 | +ICONSET = os.path.join(ROOT, "icon.iconset") |
| 18 | +TARGET = os.path.join(ROOT, "icon.icns") |
| 19 | + |
| 20 | +# .iconset 里的文件名是固定的,iconutil 靠名字识别尺寸 |
| 21 | +SIZES = [ |
| 22 | + (16, "icon_16x16.png"), (32, "icon_16x16@2x.png"), |
| 23 | + (32, "icon_32x32.png"), (64, "icon_32x32@2x.png"), |
| 24 | + (128, "icon_128x128.png"), (256, "icon_128x128@2x.png"), |
| 25 | + (256, "icon_256x256.png"), (512, "icon_256x256@2x.png"), |
| 26 | + (512, "icon_512x512.png"), (1024, "icon_512x512@2x.png"), |
| 27 | +] |
| 28 | + |
| 29 | + |
| 30 | +def main() -> int: |
| 31 | + from PIL import Image |
| 32 | + |
| 33 | + if not os.path.exists(SOURCE): |
| 34 | + print(f"找不到 {SOURCE}") |
| 35 | + return 1 |
| 36 | + |
| 37 | + source = Image.open(SOURCE) |
| 38 | + # .ico 里有多张尺寸,挑最大的那张当母版,放大出来才不糊 |
| 39 | + if getattr(source, "n_frames", 1) > 1: |
| 40 | + best, best_area = source, 0 |
| 41 | + for index in range(source.n_frames): |
| 42 | + source.seek(index) |
| 43 | + area = source.width * source.height |
| 44 | + if area > best_area: |
| 45 | + best, best_area = source.copy(), area |
| 46 | + source = best |
| 47 | + source = source.convert("RGBA") |
| 48 | + print(f"母版尺寸 {source.size}") |
| 49 | + if min(source.size) < 512: |
| 50 | + print( |
| 51 | + f" 注意: 母版只有 {source.width}px,放大到 512/1024 会糊。" |
| 52 | + f"想要清晰的 Dock 图标,换一张 1024x1024 的 icon.png 做母版。" |
| 53 | + ) |
| 54 | + |
| 55 | + os.makedirs(ICONSET, exist_ok=True) |
| 56 | + for size, name in SIZES: |
| 57 | + source.resize((size, size), Image.LANCZOS).save(os.path.join(ICONSET, name)) |
| 58 | + print(f"已生成 {ICONSET}({len(SIZES)} 个尺寸)") |
| 59 | + |
| 60 | + if sys.platform != "darwin": |
| 61 | + print("当前不是 macOS,跳过 iconutil。到 Mac 上再跑一次本脚本即可生成 icon.icns。") |
| 62 | + return 0 |
| 63 | + |
| 64 | + subprocess.run(["iconutil", "-c", "icns", ICONSET, "-o", TARGET], check=True) |
| 65 | + print(f"已生成 {TARGET}") |
| 66 | + return 0 |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + sys.exit(main()) |
0 commit comments