Skip to content

Instantly share code, notes, and snippets.

@andelf
Last active April 12, 2024 12:56
Show Gist options
  • Save andelf/acb0d317eef5d0cc8b7d53d4133c09c2 to your computer and use it in GitHub Desktop.
Save andelf/acb0d317eef5d0cc8b7d53d4133c09c2 to your computer and use it in GitHub Desktop.
Generate Chinese font for waveshare-epd
from PIL import Image, ImageDraw, ImageFont, ImageFilter
im = Image.open("./blue30.png")
POS = (1, 4)
X = POS[0] * 80
Y = POS[1] * 80
im1 = im.crop((X, Y, X + 30, Y + 30))
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pix = r, g, b, a = im1.getpixel((x, y))
r = (255 * (255 - a) + r * a) // 255
g = (255 * (255 - a) + g * a) // 255
b = (255 * (255 - a) + b * a) // 255
a = 255
im1.putpixel((x, y), (r, g, b, a))
print(pix, r)
im1.show()
im1 = im1.resize((64, 64), Image.LANCZOS)
im1 = im1.filter(ImageFilter.SHARPEN)
im1 = im1.convert('1', dither=Image.NONE)
# im1 = im1.convert('1', dither=Image.FLOYDSTEINBERG)
# im1.show()
# im1.save('./test.bmp')
buf = []
# NOTE: can only handle 8-bit boudary
for y in range(im1.size[1]):
for x in range(im1.size[0]):
if x % 8 == 0:
buf.append(0)
bit = int(im1.getpixel((x, y)) != 0)
buf[-1] = (buf[-1] << 1) | bit
print(buf)
print(len(buf))
with open('raw-img.bin', 'wb') as fp:
fp.write(bytes(buf))
from PIL import Image, ImageDraw, ImageFont
import PIL.features
# brew install libraqm
# cmdprint('libraqm:', PIL.features.check('raqm'))
size = (320, 16)
"""
FORMAT = "RGB"
BG = (255, 255, 255)
FG = (0, 0, 0)
"""
FORMAT = '1'
BG = 0
FG = 1
YOFF = -1 # or -1
CHARS = "卧槽可以了!你好世界你全心全力做到的最好可能还不如别人的随便搞搞最怕你一生碌碌无为,还安慰自己平凡可贵。"
CHARS = ''.join(list(set(CHARS)))
im = Image.new(FORMAT, size, BG)
# font = ImageFont.truetype("sarasa-mono-sc-nerd-light.ttf", size=16, index=0)
font = ImageFont.truetype("sarasa-mono-sc-nerd-regular.ttf", size=16, index=0)
# font = ImageFont.truetype("Unibit.ttf", size=16, index=0)
# font = ImageFont.truetype("zpix.ttf", size=12, index=0)
draw = ImageDraw.Draw(im)
draw.text((0, YOFF), CHARS, font=font, fill=FG, language='zh-CN')
im.save('font.png')
im.show()
draw.rectangle([(0, 0), size], fill=BG)
charmap = []
for i, c in enumerate(CHARS):
charmap = []
draw.text((0, YOFF), c, font=font, fill=FG)
for y in range(16):
v = 0
for x in range(0, 16):
b = im.getpixel((x, y))
v = (v << 1) + b
charmap.append(v >> 8)
charmap.append(v & 0xFF)
draw.rectangle([(0, 0), size], fill=BG)
print("{", end='')
print('"{}", {}'.format(c,
', '.join(map(lambda c: "0x%02x" % c, charmap))
), end="")
print("},")
import sys
sys.stdin = sys.stdin.detach() # convert to binary stream
#sys.stdout = sys.stdout.detach()
raw = sys.stdin.read()
print( ', '.join(map(lambda c: "0x%02x" % c, raw)))
#print( ''.join(map(lambda c: bin(256 + c)[3:], raw)))
# sys.stdout.write(raw[0x3a:])
@andelf
Copy link
Author

andelf commented Jan 15, 2021

blue30

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment