V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
penguinmore
V2EX  ›  Python

小白一名 求教关于使用 PIL 库在图片上写中文无法居中的问题

  •  
  •   penguinmore · 2014-09-18 11:03:46 +08:00 · 3654 次点击
    这是一个创建于 3506 天前的主题,其中的信息可能已经有所发展或是发生改变。
    小白一名 近日有个需求是在一张图片上写一段中文文字 比如:人生苦短我用Python
    网上找了一下 用PIL库实现了 但是现在有个问题就是无法让文字水平居中 代码如下 求高手指教
    im = Image.open("bottom.png")

    font = ImageFont.truetype("fang.TTF", 240)

    draw = ImageDraw.Draw(im)

    imwidth, imheight = im.size

    ont_width, font_height = draw.textsize(content, font)

    print imwidth
    print font_width

    draw.text(((imwidth - font_width) / 2, 300), unicode(content, 'UTF-8'), font=font, fill="#ffffff")

    print 出来的font_width数值不对 大于了原图的大小 但其实文字内容应该是没有超出图片的宽度的
    4 条回复    2016-05-23 16:32:12 +08:00
    KatHex
        1
    KatHex  
       2015-04-11 12:14:24 +08:00 via iPhone   ❤️ 1
    因为textsize有点bug
    使用ImageFont.trueType().getsize()但有offset,
    减去ImageFont.trueType().getoffset()
    可解决
    penguinmore
        2
    penguinmore  
    OP
       2015-04-13 09:49:29 +08:00
    @KatHex 多谢 之前已经解决了
    demonlife
        3
    demonlife  
       2016-05-23 15:53:04 +08:00
    我现在也遇到类似的情况了,中文字体无法居中显示,求指导方法!!在线急等啊!!!
    demonlife
        4
    demonlife  
       2016-05-23 16:32:12 +08:00
    @penguinmore, 你的这个问题是如何解决的啊,能否贴出解决方案,非常感谢!!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3302 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:10 · PVG 21:10 · LAX 06:10 · JFK 09:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.