如何在Python中将UTF-8字符串转为PNG/JPEG?解决非ASCII字符显示问题
非ASCII字符串转图像的字体兼容问题
我尝试将一些非ASCII字符串转换为图像,但因字体限制遇到字符显示异常的问题。
我的代码
import numpy as np import cv2 from PIL import Image, ImageDraw, ImageFont s1 = 'Hⅰ Нοѡ aᏒÈ yoμ?' image = np.zeros((100, 950, 3), dtype=np.uint8) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) pil_image = Image.fromarray(image) font = ImageFont.truetype(r'../input/arialttf-font/arial.ttf', 35) draw = ImageDraw.Draw(pil_image) draw.text((30, 30), s1, font=font) pil_image
当前输出
部分特殊字符(如全角字母、变体字符)显示为方框,无法正常渲染。
期望输出
所有非ASCII字符均能正常显示,无缺失或方框。
解决方案
问题根源在于Arial字体对部分特殊Unicode字符的支持不足,需更换为支持宽字符集的字体:
- 选择支持完整Unicode字符集的字体,例如Noto Sans、微软雅黑、Segoe UI Symbol等,这类字体覆盖了更多特殊字符和多语言符号。
- 替换代码中的字体路径为目标字体的文件路径,示例如下:
import numpy as np import cv2 from PIL import Image, ImageDraw, ImageFont s1 = 'Hⅰ Нοѡ aᏒÈ yoμ?' image = np.zeros((100, 950, 3), dtype=np.uint8) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) pil_image = Image.fromarray(image) # 替换为支持宽字符集的字体路径,以Noto Sans为例 font = ImageFont.truetype(r'NotoSansCJKsc-Regular.otf', 35) draw = ImageDraw.Draw(pil_image) draw.text((30, 30), s1, font=font, fill=(255, 255, 255)) # 显式设置白色文字,适配黑色背景 pil_image
补充说明
- 确保字体文件存在于指定路径,也可直接使用系统内置字体(如Windows下的
'msyh.ttc',Linux下直接指定'Noto Sans')。 - 若需下载字体,推荐Google Fonts的Noto系列,专为覆盖多语言和特殊Unicode字符设计。
内容的提问来源于stack exchange,提问作者yohoo
相关产品推荐
相关产品推荐

