Python:从PIL原始像素数据生成C数组

0 投票
1 回答
1291 浏览
提问于 2025-04-18 16:15

我想从一个TrueType字体生成一个固定宽度的C头文件/包含文件。把它转换成固定宽度的位图已经可以正常工作了。

import ImageFont, ImageDraw, Image

fontSize = 32
fontWidth = 20
numFonts = 1
numChars = 127-32 # Because the first 32 characters are not visible.

image = Image.new( 'RGB', (fontWidth*numChars,fontSize*numFonts), "black")
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("whitrabt.ttf", fontSize)
font2 = ImageFont.truetype("saxmono.ttf", fontSize)
font3 = ImageFont.truetype("MODENINE.TTF", fontSize)

# ASCII Characters from 32 DEC to 127 are visible
for x in range(32,127):
        draw.text(((x-32)*20, 0),chr( x), font=font)
        draw.text(((x-32)*20, 32),chr( x), font=font2)
        draw.text(((x-32)*20, 64),chr( x), font=font3)

// Convert to Grayscale for Grayscale LCD
image = image.convert('L')
image.show()

这个过程是正常的,但我就是搞不定怎么把像素数据输出成C语言数组。

1 个回答

0

你可以通过 load() 方法来获取像素数据。

pixels = image.load()

如果你想把所有的像素放在一个大的 C 语言数组里,可以这样做:

print 'const char pixels[] = {'
w, h = image.size    
for y in range(h):
    print '\t',
    for x in range(w):
        print pixels[x,y], ',',
    print
print '};'

(对于灰度图像,pixels 会包含整数;对于彩色图像,它会是 (R,G,B) 的元组。)

撰写回答