Temp

[Pillow] Generate Printed Text Image

ju_young 2022. 12. 13. 14:49
728x90

Pillow

from PIL import Image, ImageFont

text = words[10]
font_size = 384
font_filepath = "fonts/gulim.ttc"
text_color = (0, 0, 0, 255)
bg_color = (255, 255, 255, 255)

font = ImageFont.truetype(font_filepath, size=font_size)
mask_image = font.getmask(text, "RGBA")
img = Image.new("RGBA", mask_image.size, color=bg_color)
img.im.paste(color, (0, 0) + mask_image.size, mask_image)
img = img.convert('RGB')

gulim.ttc
12.90MB

Padding (Optional)

def add_margin(pil_img, top, right, bottom, left, color):
    width, height = pil_img.size
    new_width = width + right + left
    new_height = height + top + bottom
    result = Image.new(pil_img.mode, (new_width, new_height), color)
    result.paste(pil_img, (left, top))
    return result
    
img = add_margin(img, 50, 50, 50, 50, (255, 255, 255))
img.save("result.png")

 

위에서 Pillow만 사용하여 text image를 만들 경우 너무 tight하기때문에 필요에 따라 padding을 준다.

 
728x90