Sunday, November 22, 2015

Python: 中英文字符插入图片

Summary

中文字符批量插入图片,中文属性配置在Info.xlsx文件,包括所在图片名称关键字、插入字符、字体大小、字体名称、X相对位置以及Y相对位置。

Note

  1. 中文字符编码需要格外注意(冷僻汉字不一定可以顺利插入),在代码中要有编码声明,这里:#-*- coding:utf8 -*-,知会计算机中文字符的编码格式。
  2. Xls文件一定是utf-8编码格式,该文件编码调整方法见这里
  3. 文本PyAddText.py本身也必是utf-8编码格式,该文件编码调整方法见这里
  4. 字体名称一定对应着字体文件名称,如字体Arial对应字体文件arial.ttf,在属性字体中设置‘arial’,如平常Office显示之Arial则出现错误。
满足以上条件之后,代码可以正确插入中文。不过,每次运行都会发出警告信息,这个留在以后再解决。

"Warning (from warnings module): File "C:\Python27\ArcGISx6410.2\lib\site-packages\PIL\ImageFont.py", line 273 if ext and walkfilename == ttf_filename: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal "

-from SHELL Window
Fig. 1
Fig. 2
Fig. 3
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#-*- coding:utf8 -*-
# Created by LI Xu
# Version 1.0
# November 22, 2015

# Description:
# Insert Chinese Characters on pictures

# If you have any question about this code,
# please do not hesitate to contact me via E-mail: 
# jeremy456@163.com

# Blog:
# http://blog.sciencenet.cn/u/lixujeremy
# http://lixuworld.blogspot.com/


import sys
import math
import csv
import os

from PIL import Image,ImageDraw,ImageFont
import datetime
import time
begintime=time.strftime("%Y-%m-%d %H:%M:%S")
print 'Time Begin:'+begintime
starttime = datetime.datetime.now()

#~#------------------------------------------------------------------
def GetXlsRows(xlspath, indexes, records, offset):
    import xlrd
    workbook=xlrd.open_workbook(xlspath)
    # loop for every single sheet
    import math
    for sheetno in indexes:
        #print sheetno
        try:
            worksheet=workbook.sheet_by_index(sheetno)
            records=GetRecords(worksheet, offset, records)
        except:
            continue
    return records
#~#------------------------------------------------------------------
def GetRecords(worksheet, offset, records):
    for i, row in enumerate(range(worksheet.nrows)):
        if i <offset:
            continue
        r=[]    
        for j, col in enumerate(range(worksheet.ncols)):
            r.append(worksheet.cell_value(i, j))
        records.append(r)
    return records
#~#------------------------------------------------------------------
def GetFileSubStr(SouDir, flagstr):
    import os, glob
    allfiles=os.listdir(SouDir)
    filepath=[]
    for file in allfiles:
        if flagstr in file:
            filepath=os.path.join(SouDir, file)
            return filepath

#~ #----------------------------------------------------------------------  

#~ #----------------------------------------------------------------------
def InsertTextOnImg(SouDir, DesDir, record):
    flagstr=record[0]
    filepath=GetFileSubStr(SouDir, flagstr)
    if not filepath:
        print 'No such file: '+flagstr
        return
    InWord=record[1]
    FontSize=int(record[2])
    FontName=record[3]+'.ttf'
    Scale_1=record[4]
    Scale_2=record[5]
    #Output filepath
    filename=filepath.split('\\')
    filename=filename[len(filename)-1]
    otpath=os.path.join(DesDir, filename)
    print otpath
    imgfile=Image.open(filepath)
    imgSize=imgfile.size
    draw=ImageDraw.Draw(imgfile)
    font=ImageFont.truetype(FontName, FontSize)
    draw.text(((imgSize[0])*Scale_1, (imgSize[1])*Scale_2), InWord, (0,0,0), font=font)
    imgfile.save(otpath, 'PNG')

#~ #---------------------------------------------------------------------- 

#MAIN EXTRANCE
#Get the current working directory
WDir=os.getcwd()
#Source Directory
SouDir=os.path.join(WDir, 'input')
#Destination Directory
DesDir=os.path.join(WDir, 'output')
#Info
infopath='Info.xlsx'
#Change this depanding on how many header rows are present
#set to 0 if you want to include the header data.
offset=1
records=[]
index=[0, 1, 2]
info=GetXlsRows(infopath, index, records, offset)

#Loop for every single record
for ii in range(0, len(info)):
    rocd=info[ii]
    print ii+1,
    #print rocd
    InsertTextOnImg(SouDir, DesDir, rocd)


print 'Time Begin:'+begintime
starttime = datetime.datetime.now()
print "END"
endtime=time.strftime("%Y-%m-%d %H:%M:%S")
print 'Time End:'+endtime
finishtime=datetime.datetime.now()
timespan=(finishtime-starttime).seconds
timespan='%f' %timespan
print 'Time Span:'+timespan+' s'

print '************************************'

References

No comments:

Post a Comment