Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # Freetype python binding : https://freetype-py.readthedocs.io/en/latest/index.html
- # 텍스트를 렌더링해서 이미지로 만들어주는 스크립트 코드입니다.
- # This example code is to renders text to image.
- from PIL import Image
- import freetype
- WIDTH, HEIGHT = 1280, 400
- image = Image.new('L', (WIDTH,HEIGHT))
- def main():
- global freetype
- global image
- fontfilename= 'NanumSquareR.ttf'
- outfilename = 'text.png'
- text = 'Hello, world! 안녕.'
- fontSize = 20 # pt
- num_chars = len(text)
- dpi = 96 # default dpi is 96 on Windows
- face = freetype.Face(fontfilename)
- face.set_char_size(0, fontSize*64, dpi, dpi)
- # text cursor location
- px = 0
- py = 0
- for n in range(num_chars):
- charcode = ord(text[n])
- face.load_char(charcode)
- slot = face.glyph
- fontHeight = face.size.height / 64
- ftbitmap = slot.bitmap
- for by in range(0, ftbitmap.rows):
- for bx in range(0, ftbitmap.width):
- ix = int(px + slot.bitmap_left + bx)
- iy = int(py + (fontHeight - slot.bitmap_top) + by)
- # pixel out-of-range check (a very simple, inefficient)
- if ix < image.width and iy < image.height:
- location = (ix,iy)
- pixel = image.getpixel(location)
- pixel |= int(ftbitmap.buffer[by*ftbitmap.pitch + bx])
- image.putpixel(location, pixel)
- # increment pen position
- px += (slot.advance.x/64)
- py += (slot.advance.y/64)
- del face
- del freetype
- image.save(outfilename)
- del image
- if __name__ == '__main__':
- main()
Advertisement