代码之家  ›  专栏  ›  技术社区  ›  Boris Gorelik

使用pil和truetype字体在文本中抖动

  •  0
  • Boris Gorelik  · 技术社区  · 15 年前

    请考虑以下代码: 从PIL导入图像、图像绘制、图像字体

    def addText(img, lTxt):
        FONT_SIZE = 10
        INTERLINE_DISTANCE = FONT_SIZE + 1
        font = ImageFont.truetype('arial.ttf', FONT_SIZE)
        lTxtImageHeight = INTERLINE_DISTANCE * len(lTxt)
        # create text image 
        lTxtImg = Image.new('RGBA', (img.size[1], lTxtImageHeight), 255)
        lTxtImgDraw = ImageDraw.Draw(lTxtImg, )
        for (i, line) in enumerate(lTxt):
          lTxtImgDraw.text((5, i * INTERLINE_DISTANCE), line, font=font, fill='#000000')
        # rotate text image
        lTxtImg = lTxtImg.rotate(90)
        # create new transparent image ret
        ret = Image.new('RGBA', (img.size[0] + lTxtImageHeight, img.size[1]), 255)
        # paste the image to ret
        ret.paste(img, (0,0))
        # paste the text to ret
        ret.paste(lTxtImg, (img.size[0], 0), lTxtImg)
        return ret
    
    img = Image.open('in.png')
    addText(img, ['lorem', 'ipsum', 'dolores']).save('out.png')
    

    Here are the input and the output files 这是输入

    input http://img16.imageshack.us/img16/8229/73936270.png

    这就是输出

    output http://img94.imageshack.us/img94/531/outj.png

    如您所见,输出图像在文本周围包含大量的微红噪声。如何消除这种抖动?

    1 回复  |  直到 15 年前
        1
  •  0
  •   James    15 年前

    我建议将中间文本图像写入文件(文本,然后是旋转文本),以隔离艺术品首次出现的位置。

    另一种可能是PNG编码使用的是没有灰度值的Pallete,因此这些红色是最接近的。不过,我检查了ImageShack上文件的编码,看起来还可以,所以我不认为这是问题所在。