我一直在努力,现在我对我的工作有点满意了。仍然不完美,但下面的代码只对Ubuntu框中支持文本的字体给出了一个误判:
def isValidFont(f, fontNum=0, debug=False):
"""
Determine if a font is a valid font for displaying text
This code makes a best guess as to whether the font supports text.
It does this by writing a 'W' using the font, and inspecting the result.
:param f: full path to the font file
:param fontNum: index into the font file (for a file containing a collection of fonts)
:param debug: If True, files will be written for each font with information useful for debugging
:return: True if font appears to support text, False otherwise
"""
width = 40
height = 40
font = ImageFont.truetype(f, index=fontNum, size=height-6)
fontName = font.getname()
tmpImg = Image.new('1', (width,height))
dr = ImageDraw.Draw(tmpImg)
dr.text((3, 3), 'W', font=font, fill=(1))
if debug:
fname = str(fontName) + '.bmp'
tmpImg.save(fname)
img_data = list(tmpImg.getdata())
if debug:
fname = str(fontName) + '.txt'
fd = open(fname, mode='w')
for row in range(height):
fd.write(str(img_data[row*width : (row+1)*width]) + '\n')
fd.close()
if sum(img_data) == 0:
return False
compressedList = []
for i in range(height):
prev_elem = None
thisRow = []
for j in range(width):
index = i*width + j
elem = img_data[index]
if prev_elem is None:
thisRow.append(elem)
prev_elem = elem
elif elem == prev_elem:
if elem == 1:
thisRow[len(thisRow)-1] += 1
else:
thisRow.append(elem)
prev_elem = elem
compressedList.append(thisRow)
for row in compressedList:
while len(row) > 0 and row[0] == 0:
del row[0]
while len(row) > 0:
index = len(row)-1
if row[index] == 0:
del row[index]
else:
break
while len(compressedList[0]) == 0:
del compressedList[0]
index = len(compressedList)-1
while len(compressedList[index]) == 0:
del compressedList[index]
index = len(compressedList)-1
if debug:
fname = str(fontName) + '_c.txt'
fd = open(fname, mode='w')
for row in compressedList:
fd.write(str(row) + '\n')
fd.close()
for row in compressedList:
if len(row) > 3:
return True
return False