使用PIL绘制多语言文本并保存为1位和8位位图

时间:2017-11-29 04:59:01

标签: python-2.7 fonts python-imaging-library

我开始使用this nice answer中的脚本。它适用于“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

imtype = "1": enter image description here

imtype = "L": enter image description here

imtype = "RGB": enter image description here

1 个答案:

答案 0 :(得分:2)

<强>更新

This answer建议使用PIL的Image.point()方法代替.convert()

整件事看起来像这样:

from PIL import Image, ImageDraw, ImageFont
import numpy as np
w_disp   = 128
h_disp   =  64
fontsize =  32
text     =  u"你好!"

imageRGB = Image.new('RGB', (w_disp, h_disp))
draw  = ImageDraw.Draw(imageRGB)
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)

image8bit = imageRGB.convert("L")
imageRGB.save("NiHao! RGB.bmp")
image8bit.save("NiHao! 8bit.bmp")

imagenice_80  = image8bit.point(lambda x: 0 if x < 80  else 1, mode='1')
imagenice_128 = image8bit.point(lambda x: 0 if x < 128 else 1, mode='1')
imagenice_80.save("NiHao! nice 1bit 80.bmp")
imagenice_128.save("NiHao! nice 1bit 128.bmp")

NiHao! RGB NiHao! 8 bit NiHao! 1 bit 80 NiHao! 1 bit 128

<强> ORIGINAL:

看起来TrueType字体不希望使用小于RGB的任何东西。

您可以尝试使用PIL的.convert()方法对图像进行下转换。

从RGB图像开始,这给出了:

image.convert("L"): enter image description here

image.convert("1"): enter image description here

转换为8位灰度可以很好地工作,但从TrueType字体或任何基于灰度的字体开始,1位转换看起来总是很粗糙。

对于外观漂亮的1位图像,可能需要从为数字开/关显示器设计的1位位图中文字体开始。