#-*- coding: UTF-8 -*-
import urllib2, re,datetime,time, os,sys
from PIL import Image, ImageDraw, ImageFont
from math import atan, degrees
#
#图片下载类
#功能:下载图片,生成缩略图,生成水印图
#
class downloadPic:
def __init__(self,picDir,Font):
self.picDir=picDir
self.FONT = Font
def getFilename(self,urlT):
#print urlT
ndate=datetime.datetime.now()
if not os.path.exists('%s%s' %(self.picDir,ndate.year)):
os.mkdir('%s%s' %(self.picDir,ndate.year))
if not os.path.exists('%s%s/%s' % (self.picDir,ndate.year,ndate.month)):
os.mkdir('%s%s/%s' % (self.picDir,ndate.year,ndate.month))
if not os.path.exists('%s%s/%s/%s' % (self.picDir,ndate.year,ndate.month,ndate.day)):
os.mkdir('%s%s/%s/%s' % (self.picDir,ndate.year,ndate.month,ndate.day))
if not os.path.exists('%s%s/%s/%s/%s' % (self.picDir,ndate.year,ndate.month,ndate.day,'src')):
os.mkdir('%s%s/%s/%s/%s' % (self.picDir,ndate.year,ndate.month,ndate.day,'small'))
os.mkdir('%s%s/%s/%s/%s' % (self.picDir,ndate.year,ndate.month,ndate.day,'mark'))
os.mkdir('%s%s/%s/%s/%s' % (self.picDir,ndate.year,ndate.month,ndate.day,'src'))
extname=urlT.split('.')
extname=extname[len(extname)-1]
ntime="%s.%s0000" % (int(time.mktime(ndate.timetuple())),ndate.microsecond)
ntime=ntime[:17]
filename='%s%s/%s/%s/src/%s.%s' % (self.picDir,ndate.year,ndate.month,ndate.day,ntime,extname)
print filename
self
return [filename,ntime]#图片全地址,保存数据库ID
def downloadPic(self,urlT,filenameT):
request = urllib2.Request(urlT)
opener = urllib2.build_opener()
f = opener.open(request)
#print f.headers.dict['content-type']
#if f.headers.dict['content-type']=='image/jpeg':
#保存到文件
xfile = open(filenameT, 'wb')
xfile.write(f.read())
xfile.close()
print '下载图片%s ok' % urlT
return True
#else:
#TODO 抛出异常
#raise Exception,'not img'
def markPic(self,srcFileName,text,markFileName):
img = Image.open(srcFileName).convert("RGB")
watermark = Image.new("RGBA", (img.size[0], img.size[1]))
draw = ImageDraw.ImageDraw(watermark, "RGBA")
size = 0
while True:
size += 1
nextfont = ImageFont.truetype(self.FONT, size)
nexttextwidth, nexttextheight = nextfont.getsize(text)
if nexttextwidth+nexttextheight/3 > watermark.size[0]:
break
font = nextfont
textwidth, textheight = nexttextwidth, nexttextheight
draw.setfont(font)
draw.text(((watermark.size[0]-textwidth)/2,
(watermark.size[1]-textheight)/2), text)
watermark = watermark.rotate(degrees(atan(float(img.size[1])/img.size[0])),
Image.BICUBIC)
mask = watermark.convert("L").point(lambda x: min(x, 55))
watermark.putalpha(mask)
img.paste(watermark, None, watermark)
img.thumbnail((300, 300))
img.save(markFileName)
def smallPic(self,srcFileName,smallFileNmae):
im = Image.open(srcFileName)
im.thumbnail((100, 100))
im.save(smallFileNmae)