【问题标题】:Python how do I overlay random images over images being generated to end up with 2 images with textPython如何在生成的图像上叠加随机图像以最终得到2个带有文本的图像
【发布时间】:2013-01-07 05:27:43
【问题描述】:

这是我到目前为止的代码。它的作用是从文本文件中抓取随机文本行并生成随机颜色,然后创建顶部带有文本的 JPG 图像。我想要做的是随机拍摄一张照片,并将其覆盖在纯色之上,不透明度可能为 0.2 或其他东西,然后将文本放在上面,所以我最终得到 > 纯色 > 图片覆盖 > 文本在上面。此代码生成多个图像。让文本也垂直居中会很好,但我不清楚如何做到这一点。

import Image, random, textwrap, ImageFont, ImageDraw, os, sys
basepath = os.path.dirname(sys.argv[0]) + "/"

for n in xrange(10):

    keywordlist = []
    imglist = []
    keyword = file(basepath + "text.txt", "r")

    for line in keyword:
        keywordlist.append(line.replace("\n", ""))

        def type(name):
            value = name[random.randint(0,len(name)-1)]
            return value

    def random_color():
        return (random.randint(0,155), random.randint(0,155), random.randint(0,155))

    astr = ('%s' %(type(keywordlist)))
    para = textwrap.wrap(astr,width=19)

    MAX_W,MAX_H=640,400
    im = Image.new('RGB', (MAX_W, MAX_H), (random_color()))
    draw = ImageDraw.Draw(im)
    font = ImageFont.truetype('C:/windows/fonts/Arialbd.ttf', 58)

    current_h=0
    for line in para:
        w,h=draw.textsize(line, font=font)
        draw.text(((MAX_W-w)/2, current_h), line, font=font,)
        current_h+=h

    im.save('img%000d.jpg' % n)

这是一个输出示例:

【问题讨论】:

    标签: python image python-imaging-library


    【解决方案1】:

    使用the blend function:

    new_image = Image.blend(solid_color_image, picture, 0.2)
    

    【讨论】:

    • 到目前为止,我能够生成随机颜色叠加,但文字没有出现在图像上。
    • @user1953451:您需要在创建纯色图像之后和创建ImageDraw.Draw 对象之前立即混合它。
    • 我将 image.blend 添加到下面的代码中,它将生成带有文本的图像,但没有图像、叠加层和文本。 MAX_W,MAX_H=640,400 im = Image.new('RGB', (MAX_W, MAX_H), (random_color())) new_image = Image.blend(im, picture, 0.2) draw = ImageDraw.Draw(im) font = ImageFont .truetype('C:/windows/fonts/Arialbd.ttf', 58)
    • new_image 包含结果,但您没有使用它。您可能想使用im = 而不是new_image =
    • 完美!!那行得通。现在它将在其上生成纯色、叠加图像和文本。你知道我将如何“垂直”居中文本吗?
    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 2021-03-30
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    相关资源
    最近更新 更多