【问题标题】:full image with rectangle with text inside of it带有矩形的完整图像,其中包含文本
【发布时间】:2020-05-29 20:49:45
【问题描述】:

试图在我的图像上放置一个带有白色文本的红色矩形。 和这里显示的一样

到目前为止,我可以将文本放在左上角,但我仍然错过了其中包含文本的全角矩形。

矩形应该放在哪里

from PIL import Image, ImageDraw, ImageFont
base = Image.open('C:\\Users\\t3cho\\Desktop\\DSC15178.jpg').convert('RGBA')
width, height = base.size
txt = Image.new('RGBA', base.size, (255,255,255,0))
fnt = ImageFont.truetype('arial.ttf', 80)
d = ImageDraw.Draw(txt)
d.text((0,0), "10% OFF FOR THIS ITEM", font=fnt, fill=(255,0,0,128))
out = Image.alpha_composite(base, txt)
out.show()

【问题讨论】:

    标签: python python-imaging-library


    【解决方案1】:
    from PIL import Image, ImageFont, ImageDraw, ImageEnhance
    from io import BytesIO
    
    source_img = Image.open("C:\\Users\\t3cho\\Desktop\\DSC15178.jpg").convert("RGBA")
    font = ImageFont.truetype(font=BytesIO(open("C:\\Windows\\Fonts\\COOPBL.TTF", "rb").read()),size=65)  #ImageFont.truetype("cooper black",65)
    text = "This is my text centered"
    
    # get text size
    text_size = font.getsize(text)
    # set button size + 10px margins
    button_size =  (source_img.size[0], 100)  # (text_size[0]+20, text_size[1]+20)
    # create image with correct size and black background
    button_img = Image.new('RGBA', button_size, "red")
    positionx = (float(source_img.size[0]) - float(text_size[0])) / float(2)
    # put text on button with 10px margins
    button_draw = ImageDraw.Draw(button_img)
    button_draw.text((positionx, 10), text, font=font)
    # put button on source image in position (0, 0)
    source_img.paste(button_img, (0, 0))
    # save in new file
    im = source_img.convert("RGB")
    im.save("C:\\Users\\t3cho\\Desktop\\DSC15178-out.jpg")
    

    【讨论】:

      猜你喜欢
      • 2012-07-11
      • 2012-01-18
      • 1970-01-01
      • 2022-01-16
      • 2015-06-10
      • 1970-01-01
      • 2012-02-24
      • 2017-02-28
      • 2010-10-22
      相关资源
      最近更新 更多