[Python] Draw a rectangle and a text in it using PIL

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    I want to draw a rectangle and a text in it, here's a part of my code and it's a bit obfuscated:

    from PIL import Image
    from PIL import ImageFont
    from PIL import ImageDraw
    from PIL import ImageEnhance

    source_img = Image.open(file_name).convert("RGB")

    img1 = Image.new("RGBA", img.size, (0,0,0,0))
    draw1 = ImageDraw.Draw(watermark, "RGBA")
    draw1.rectangle(((0, 00), (100, 100)), fill="black")
    img_rectangle = Image.composite(img1, source_img, img1)

    draw2 = ImageDraw.Draw(img1, "RGBA")
    draw2.text((20, 70), "something123", font=ImageFont.truetype("font_path123"))

    Image.composite(img1, source_img, img1).save(out_file, "JPEG")


    This draws them both, but they're separate: the text is under the rectangle. Whereas I want a text to be drawn inside the rectangle. How can I do that? Should I necessarily compose them or what?

    Continue reading...

Compartilhe esta Página