CHKim

pytext2image.py

Oct 5th, 2019
363
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # Freetype python binding : https://freetype-py.readthedocs.io/en/latest/index.html
  4. # 텍스트를 렌더링해서 이미지로 만들어주는 스크립트 코드입니다.
  5. # This example code is to renders text to image.
  6.  
  7. from PIL import Image
  8. import freetype
  9.  
  10. WIDTH, HEIGHT = 1280, 400
  11. image = Image.new('L', (WIDTH,HEIGHT))
  12.  
  13. def main():
  14.     global freetype
  15.     global image
  16.  
  17.     fontfilename= 'NanumSquareR.ttf'
  18.     outfilename = 'text.png'
  19.     text = 'Hello, world! 안녕.'
  20.     fontSize = 20 # pt
  21.  
  22.     num_chars = len(text)
  23.     dpi = 96 # default dpi is 96 on Windows
  24.  
  25.     face = freetype.Face(fontfilename)
  26.     face.set_char_size(0, fontSize*64, dpi, dpi)
  27.  
  28.     # text cursor location
  29.     px = 0
  30.     py = 0
  31.  
  32.     for n in range(num_chars):
  33.         charcode = ord(text[n])
  34.  
  35.         face.load_char(charcode)
  36.         slot = face.glyph
  37.         fontHeight = face.size.height / 64
  38.         ftbitmap = slot.bitmap
  39.  
  40.         for by in range(0, ftbitmap.rows):
  41.             for bx in range(0, ftbitmap.width):
  42.                 ix = int(px + slot.bitmap_left + bx)
  43.                 iy = int(py + (fontHeight - slot.bitmap_top) + by)
  44.  
  45.                 # pixel out-of-range check (a very simple, inefficient)
  46.                 if ix < image.width and iy < image.height:
  47.                     location = (ix,iy)
  48.                     pixel = image.getpixel(location)
  49.                     pixel |= int(ftbitmap.buffer[by*ftbitmap.pitch + bx])
  50.                     image.putpixel(location, pixel)
  51.  
  52.         # increment pen position
  53.         px += (slot.advance.x/64)
  54.         py += (slot.advance.y/64)
  55.  
  56.     del face
  57.     del freetype
  58.  
  59.     image.save(outfilename)
  60.     del image
  61.  
  62. if __name__ == '__main__':
  63.     main()
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment