1

I made a command that adds text to an image. But the problem is that sometimes the text just goes offscreen if someone inputs a long message. How can I fix this?

@bot.command()
async def Picture1(ctx,*,message=None):

    member = ctx.author
    if message ==None:
        await ctx.send("You have to put a message in idiot")
        return

    text1 = str(member)
    print(text1)

    # get an image
    base = Image.open(r"C:\Users\User\Pictures\Picture.png").convert("RGBA")

    # make a blank image for the text, initialized to transparent text color
    txt = Image.new("RGBA", base.size, (255, 255, 255, 0))

    # get a font
    fnt = ImageFont.truetype(
        r"C:\Users\User\fonts\courbi.ttf", 40)
    # get a drawing context
    d = ImageDraw.Draw(txt)

    # draw text, half opacity
    d.text((21, 70), "'" + message + "'", font=fnt,
           fill=(255, 255, 255, 128))
    # draw text, full opacity
    d.text((10, 213), "-" + text1, font=fnt, fill=(255, 255, 255, 255))

    out = Image.alpha_composite(base, txt)

    out.save("picutre1.png", format="png")
    print(out.save)

    await ctx.send(file=discord.File("quote.png"))
Ahmet Kaya
  • 13
  • 2

1 Answers1

0

Using this answer to calculate the size of the text in pixels, you can then choose to either make the text smaller or just make a new line.

Stuff from that answer:

import ctypes

def GetTextDimensions(text, points, font):
    class SIZE(ctypes.Structure):
        _fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]

    hdc = ctypes.windll.user32.GetDC(0)
    hfont = ctypes.windll.gdi32.CreateFontA(-points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
    hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)
    size = SIZE(0, 0)
    ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text.encode('cp1252'), len(text), ctypes.byref(size))
    ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
    ctypes.windll.gdi32.DeleteObject(hfont)
    return (size.cx, size.cy)

If you want to just make the text fit, I've already made a function to get a size that will fit:

def resizetofit(text,sz,fontname,max_horizontal):
    while True:
        width, height = GetTextDimensions(text, sz, fontname) #Get size of text
        if width < max_horizontal:
            break
        else:
            sz -= 1
    return sz

Usage: textsize = resizetofit("text", default text size, "fontName", horizontal max size in pixels)

Or if you want to break a line if it doesn't fit, then tell me and I can try making a function to do that, but the answer I linked has everything you need to make your own.

Parasol Kirby
  • 351
  • 1
  • 11