推荐学习书目
› 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 · Sep 18, 2014 · 4433 views
    This topic created in 4398 days ago, the information mentioned may be changed or developed.
    小白一名 近日有个需求是在一张图片上写一段中文文字 比如:人生苦短我用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 replies  •  2016-05-23 16:32:12 +08:00
    KatHex
        1
    KatHex  
       Apr 11, 2015 via iPhone   ❤️ 1
    因为textsize有点bug
    使用ImageFont.trueType().getsize()但有offset,
    减去ImageFont.trueType().getoffset()
    可解决
    penguinmore
        2
    penguinmore  
    OP
       Apr 13, 2015
    @KatHex 多谢 之前已经解决了
    demonlife
        3
    demonlife  
       May 23, 2016
    我现在也遇到类似的情况了,中文字体无法居中显示,求指导方法!!在线急等啊!!!
    demonlife
        4
    demonlife  
       May 23, 2016
    @penguinmore, 你的这个问题是如何解决的啊,能否贴出解决方案,非常感谢!!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   832 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:59 · PVG 06:59 · LAX 15:59 · JFK 18:59
    ♥ Do have faith in what you're doing.