作用:將文字轉化為圖片保存
#載入必要的模塊 import pygame import os from PIL import Image import sys def getPic(title,width_i = 200,height_i = 200,isWordSplited="0",isWordMarginMin="1"): # 待轉換文字title # 圖片壓縮后的大小width_i = 200,height_i = 200 # 英文單詞是否單個顯示isWordSplited # 是否將字符間間距調到最小isWordMarginMin width_i=int(width_i) height_i=int(height_i) #pygame初始化 pygame.init() result=[] tmpstr="" if isWordSplited=="1": #對文字進行切分(英語單詞字母分開) for s in title: result.append(s) else: #對文字進行切分(英語單詞作為整體) for s in title: if ord(s) in range(ord('A'),ord('Z')) or ord(s) in range(ord('a'),ord('z')): tmpstr=tmpstr+s else: if(tmpstr!=""): result.append(tmpstr) tmpstr="" result.append(s) print(result) print(width_i) wordcount=len(result) for i in range(0,wordcount): #設置字體和字號 font = pygame.font.Font("msyh.ttc", 64) #渲染圖片,設置背景顏色和字體樣式,前面的顏色是字體顏色 ftext = font.render(result[i], True, (65, 83, 130),(255, 255, 255),) #ftext = pygame.transform.rotate(ftext,90) #保存圖片 pygame.image.save(ftext, str(i)+".jpg")#圖片保存地址 #每行每列顯示圖片數量 line_max = 1 row_max = wordcount #參數初始化 num = 0 pic_max=line_max*row_max #生成背景圖片 toImage = Image.new('RGB',(width_i*line_max,height_i*row_max),color=(255,255,255)) totalHeight=0 for i in range(0,row_max): for j in range(0,line_max): pic_fole_head = Image.open(str(num)+".jpg") width,height = pic_fole_head.size scale=1 #按照一定比例拉伸圖片 if width>height: scale=width_i/width else: scale=height_i/height tmppic = pic_fole_head.resize((int(width*scale),int(height*scale))) totalHeight=int(height*scale)+totalHeight #計算每個字在新圖中的位置 loc = (int(j%line_max*width_i+(width_i-width*scale)/2),int(i%row_max*height_i)) #將生成的圖片粘貼到大圖中 toImage.paste(tmppic,loc) num= num+1 if num >= pic_max: break #按照每個單詞或者字的實際高度進行重新排列 if isWordMarginMin=="1": currentHeight=0 toImageSorted = Image.new('RGB',(width_i*line_max,totalHeight),color=(255,255,255)) #重新排列 num=0 for i in range(0,row_max): for j in range(0,line_max): pic_fole_head = Image.open(str(num)+".jpg") width,height = pic_fole_head.size scale=1 #按照一定比例拉伸圖片 if width>height: scale=width_i/width else: scale=height_i/height tmppic = pic_fole_head.resize((int(width*scale),int(height*scale))) #計算每個字在新圖中的位置 loc = (int(j%line_max*width_i+(width_i-width*scale)/2),currentHeight) currentHeight=int(height*scale)+currentHeight #將生成的圖片粘貼到大圖中 toImageSorted.paste(tmppic,loc) num= num+1 if num >= pic_max: break print(toImageSorted.size) toImageSorted.save(title+'.png') else: print(toImage.size) toImage.save(title+'.png') for i in range(0,row_max): os.remove(str(i)+".jpg") #讀取命令行參數 title=sys.argv[1] width_i=sys.argv[2] height_i=sys.argv[3] isWordSplited=sys.argv[4] isWordMarginMin=sys.argv[5] getPic(title,width_i,height_i,isWordSplited,isWordMarginMin)
主要參考:
https://blog.csdn.net/johinieli/article/details/76151247
https://www.cnblogs.com/asreg/p/6791406.html
代碼和字體文件:https://download.csdn.net/download/heartwasd95/10712913
