提供一种本地将图片转换为lua代码的方法。
使用Python + Pillow实现
开发环境:Python3.11 + PIL
完整代码:
from PIL import Image
import sys
import textwrap
"""
(237,237,237) -> 白色
(239, 176, 50) -> 橙色
(226, 125, 213) -> 品红
(151, 176, 239) -> 淡蓝
(219, 219, 107) -> 黄色
(125, 202, 25) -> 绿色
(239, 176, 202) -> 粉色
(75, 75, 75) -> 深灰
(151, 151, 151) -> 淡灰
(75, 151, 176) -> 陶蓝
(176, 101, 226) -> 紫色
(50, 101, 202) -> 湖蓝
(125, 101, 75) -> 棕色
(86, 164, 77) -> 绿色
(202, 75, 75) -> 红色
(17,17,17) -> 黑色
"""
color_map = \
{
(237, 237, 237): '0',
(239, 176, 50): '1',
(226, 125, 213): '2',
(151, 176, 239): '3',
(219, 219, 107): '4',
(125, 202, 25): '5',
(239, 176, 202): '6',
(75, 75, 75): '7',
(151, 151, 151): '8',
(75, 151, 176): '9',
(176, 101, 226): 'a',
(50, 101, 202): 'b',
(125, 101, 75): 'c',
(86, 164, 77): 'd',
(202, 75, 75): 'e',
(17, 17, 17): 'f'
}
keys = list(color_map.keys())
path = None
w = None
h = None
def main(pa, iw, ih):
img = Image.open(pa)
img.convert("P")
img = img.resize((iw, ih))
pix = list(img.getdata())
iw, ih = img.size
with open("out.lua", "w+") as f:
out = ""
total = len(pix)
assert total != 0
com: int = 0
for (r, g, b, *a) in pix:
word = ''
num = 255 * 3
for (rr, gg, bb) in keys:
dis = abs(r - rr) + abs(g - gg) + abs(b - bb)
if dis < num:
num = dis
word = color_map[(rr, gg, bb)]
out += word
com += 1
print("\r", end="")
print(f"处理像素: {com}/{total}: ", "▋" * (int(com / total) // 2), end="")
sys.stdout.flush()
result = textwrap.wrap(out, iw)
result.reverse()
le = len(result)
i = 0
print("\n---------------\n")
for t in result:
f.write(f"term.scroll(-1)\n")
f.write(f"term.setCursorPos(1,1)\n")
f.write(f"term.blit('{t}','{t}','{t}')\n")
i += 1
print("\r", end="")
print(f"写入文件: {i}/{le}: ", "▋" * (int(i / le) // 2), end="")
sys.stdout.flush()
if __name__ == "__main__":
if path is None:
path = input("输入图片完整路径")
if w is None or h is None:
w, h = int(*input("输入图片宽高,以空格分割").split(" "))
main(path, w, h)
两种调用方法,可以手动修改代码内的path,w,h。也可以运行时在控制台输入
运行完成后同级目录下会出现一个文件out.lua。导入CC电脑后可以直接运行得到图像。
例子:
monitor right out.lua
在外接显示器上显示
PS:
出现报错
Traceback (most recent call last):
File "", line 1, in <module>
from PIL import Image
ModuleNotFoundError: No module named 'PIL'
原因:
没有安装pillow库,在控制台中执行(使用清华镜像)安装
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple Pillow
需要安装python时选择"Add to Path"