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

标签 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

最佳答案

更新:

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


原创:

看起来 TrueType 字体不想使用 RGB 以外的字体。

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

从 RGB 图像开始,这给出:

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

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

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

为了好看的 1 位图像,可能有必要从为数字开/关显示器设计的 1 位位图中文字体开始。

关于python-2.7 - 使用 PIL 绘制多语言文本并保存为 1 位和 8 位位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545359/

相关文章:

Python2 哈希值分布不良

ios - 使用谷歌字体 - Meteor Cordova

python - 遍历元素嵌套结构中的所有 XML 节点

cocoa - 如何将 Lucida Grande italic 添加到我的申请中?

javascript - 如何禁用 jsPDF 嵌入默认字体列表?

python-imaging-library - python 图像库如何绘制文本新线?

python - 在python中将多个图像绘制到tiff文件中

python - 在 Python 中尽快获取图像(jpg、原始文件、tiff)的高度和宽度的策略?

Python:用户选择 int 或 float

c++ - c++11 是否提供与 python maketrans/translate 中实现的类似的解决方案?