- 解决python OSError: cannot open re
- Pillow模块之OSError: cannot open re
- pillow使用备忘之OSError: cannot open
- Python3 报错OSError: cannot open r
- windows cannot load library 'lib
- fatal error C1083: Cannot open i
- 死亡Error:OSError: [Errno 12] Cann
- 解决用UltraISO将操作系统ISO镜像写入U盘后U盘变成FA
- 【原创】各种安装 No such file or directo
- Eclipse下cannot open git-upload-p
我在使用PIL的过程中,想写一个用文字做像素填充图片的脚本,结果设置字体的时候一直报错,即使该字体在字体库中或者使用绝对路径仍然报这个错误。
查看网上的方法发现,没有能解决这个问题的,还有人说要用这个对应的英文名,尝试了以后没有用,查看注册表以后发现我这个字体在注册表中也是中文名。最后在StackOverFlow中找到了原因。
即该模块无法识别非ASCⅡ的路径(包括文件名),所以必须使用纯ASCⅡ编码的字体文件路径以及文件名。可以把想要用的字体复制到一个纯英文的目录下,再改为英文文件名。在需要的位置使用绝对路径。
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
一个生成有意思的图片的程序
"""
from PIL import Image,ImageDraw,ImageFont
text_font = 'd:/test.ttf' # 问题主要在这里,必须使用ASCⅡ编码的字体名,中文名不行。可以将该字体文件复制出来到一个英文目录下并将文件名改为英文即可。
font_size = 10
text = "text"
img_path = "C:/Users/name/Desktop/test.jpg"
img_raw = Image.open(img_path)
img_array = img_raw.load()
img_new = Image.new("RGB",img_raw.size,(0,0,0))
draw = ImageDraw.Draw(img_new)
font = ImageFont.truetype(text_font,font_size)
def character_generator(text):
while True:
for i in range(len(text)):
yield text[i]
ch_gen = character_generator(text)
for y in range(0,img_raw.size[1],font_size):
for x in range(0,img_raw.size[0],font_size):
draw.text((x,y),next(ch_gen),font=font,fill=img_array[x,y],direction=None)
img_new.convert('RGB').save('C:/Users/name/Desktop/1.jpg')
网友评论