天使漫步IT工作室天使漫步IT工作室

python使用pil在图片上添加中文乱码解决办法


Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 110

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 116

今天搞一个pil上面刻字的程序,刚开始写数字的时候好好的,但是遇到汉字就乱码了。后来查了一个下手册发现,汉字需要特殊处理一下,其实就一行代码,示例如下:

# -*- coding: UTF-8 -*-
from PIL import Image, ImageDraw, ImageFont

def add_num(img,text):
    draw = ImageDraw.Draw(img)
    myfont = ImageFont.truetype('xingkai.ttf', size=150)
    fillcolor = "#000000"
    width, height = img.size
    draw.text((width/2-300, height*2/3 - 270), unicode(text,'UTF-8'), font=myfont,fill=fillcolor)
    img.save('result.png','png')
    return 0

if __name__ == '__main__':
    image = Image.open('zhengshu.png')
    add_num(image,"梦想成真")
    image.show()

我们可以看出,unicode(text,'UTF-8') 将汉字进行unicode编码,以便画笔可以识别。

本站原创,欢迎转载,转载敬请标明出处:天使漫步IT工作室 » python使用pil在图片上添加中文乱码解决办法
添加新评论


Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /www/wwwroot/u11u.com/usr/themes/wq/comments.php on line 38