[TOC]
## 概況
### 背景
在設計技能樹的時候需要做一些簡單的Logo,方便我們來識別,這時候就想到了PIL。加上一些簡單的圓角,以及特殊的字體,就可以構成一個簡單的Logo。做成的圖標看上去還不錯:
### ShowCase
???
代碼見:[https://github.com/phodal/text2logo](https://github.com/phodal/text2logo)
### 需求說明
簡單的說一些我們的附加需求
* 圓角
* 色彩(自動)
## 步驟
### Step 1: Python 文字轉Logo實戰
一個簡單的PIL生成圖片的代碼:
~~~
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
img = Image.new('L', (128, 128), 255)
draw = ImageDraw.Draw(img)
text_to_draw = unicode('xxs', 'utf-8')
font = ImageFont.truetype('fonts/NotoSansCJKsc-Regular.otf', 12)
draw.text((2, 2), text_to_draw, font=font)
del draw
img.save('build/image.png')
~~~
#### 圓角代碼
我們需要的是在上面的代碼上加上一個圓角的功能,于是Google到了這個函數
~~~
def add_corners(im, rad):
circle = Image.new('L', (rad * 2, rad * 2), 0)
image = ImageDraw.Draw(circle)
image.ellipse((0, 0, rad * 2, rad * 2), fill=255)
alpha = Image.new('L', im.size, 255)
w, h = im.size
alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))
alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))
alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))
im.putalpha(alpha)
return im
~~~
#### 顏色配置
在Github上找到了一個配色還不錯的CSS,將之改為color.Ini,在里面配置了不同色彩與文字、前景的有關系等等,如:
~~~
[Color]
turqoise: #1abc9c,#ecf0f1
greenSea: #16a085,#ecf0f1
[Text]
自動化測試: auto_test
前端開發: web_front_develop
~~~
讀取配置則用的是`ConfigParser`:
~~~
import ConfigParser
ConfigColor = ConfigParser.ConfigParser()
ConfigColor.read("./color.ini")
bg_colors = []
font_colors = []
for color_name, color in ConfigColor.items('Color'):
bg_colors.append(color.replace('#', '').split(',')[0])
font_colors.append(color.replace('#', '').split(',')[1])
colors_length = ConfigColor.items('Color').__len__()
~~~
最后我們就可以得到我們想要的圖片了~~