本文實例講述了Python實現自動為照片添加日期并分類的方法。分享給大家供大家參考,具體如下:
小時候沒怎么照相,所以跟別人說小時候特別帥他們都不信。小外甥女出生了,我給買了個照相機,讓她多照相。可惜他舅目前還是個屌絲,買了個700的屌絲照相機,竟然沒有自動加日期的功能。試了幾個小軟件,都不好用,大的圖像軟件咱又不會用。身為一個計算機科學與技術專業的學生,只能自立更生了。
聽說Python有個圖形庫,不錯,在照片上打日期很容易,于是我就下了這個庫。對Python不熟,一面看著手冊一面寫的。完成了下面的小程序,很簡單。還不實用,我再修改一下,加上圖形界面,并且將Python代碼轉換成exe,因為我要把程序給我姐用,所以要做到最傻瓜式。
(1)在相片右下角打印日期,格式類似于 2012-12-05 10:23:46
(2)以上面的日期為例,將原文件重命名為20121205102346.jpg,生成的文件命名為20121205102346DATE.jpg,并且放入文件夾20121205中,這樣就可以把相片自動分類了。兩個相片拍攝時間到秒數就應該不同了,除非是連拍。
代碼(事先安裝PIL庫,http://www.pythonware.com/products/pil/)
import os,sys,shutilfrom PIL import Imagefrom PIL import ImageDrawfrom PIL.ExifTags import TAGSfrom PIL import ImageFont#open image fileif len(sys.argv) < 2: print "Usage: ",sys.argv[0]," ImageFile" sys.exit(1)im = Image.open(sys.argv[1])print 'Image size is:',im.size#get the info dictinfo = im._getexif()#info store the information of the image#it stores the info like this: [233:'name',2099:'2012:01:01 10:44:55',...]#the key need to be decoded,#This piece of code will extract the time when the photo is takenfor tag,value in info.items(): decoded = TAGS.get(tag,tag) if decoded == 'DateTime': date = value break#The date time is in this format '2012:01:01 10:44:22', replace the first two ":" with "-", need a writable listdate_list = []for x in range(0,len(date)): date_list.append(date[x])date_list[4] = '-'date_list[7] = '-'date = ''.join(date_list) #draw.text expect a string, convert it back to string#the font size will be 1/15 of the images sizefont = ImageFont.truetype("FZYTK.TTF",im.size[1] / 15)draw = ImageDraw.Draw(im)stringsize=draw.textsize(date,font=font)print 'Text size is:',stringsize#put the text to the right cornerdraw.text((im.size[0]-stringsize[0],im.size[1]-stringsize[1]),date,fill=255,font=font)#rename the source photo and the dated photo, eliminate the ':' and '-' and ' 'new_date_list = []for x in range(0,len(date_list)): if date_list[x] != ':' and date_list[x] != '-' and date_list[x] != ' ': new_date_list.append(date_list[x])date = ''.join(new_date_list[0:8])time = ''.join(new_date_list[8:])#print date#print timedir_name = ''.join(date)src_filename = ''.join(new_date_list)dst_filename = src_filename + 'DATE'#print dir_name#print src_filename#print dst_filenameif not os.path.isdir(dir_name): os.makedirs(dir_name)path = dir_name + '/' + dst_filename +'.JPG'#print pathim.save(path)shutil.copy(sys.argv[1],dir_name+'/'+src_filename+'.JPG')效果圖如下:

希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答