我从这个不错的答案开始。它对于“RGB”工作得很好,但是8位灰度模式“L”和1位黑/白模式“1”的PIL图像似乎只会显示为黑色。我做错了什么?
from PIL import Image, ImageDraw, ImageFont
import numpy as np
w_disp = 128
h_disp = 64
fontsize = 32
text = u"你好!"
for imtype in "1", "L", "RGB":
image = Image.new(imtype, (w_disp, h_disp))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("/Library/Fonts/Arial Unicode.ttf", fontsize)
w, h = draw.textsize(text, font=font)
draw.text(((w_disp - w)/2, (h_disp - h)/2), text, font=font)
image.save("NiHao! 2 " + imtype + ".bmp")
data = np.array(list(image.getdata()))
print data.shape, data.dtype, "min=", data.min(), "max=", data.max()
输出:
(8192,) int64 min= 0 max= 0
(8192,) int64 min= 0 max= 0
(8192, 3) int64 min= 0 max= 255