[Copy to clipboard] [ - ]
CODE:
#-*- coding:GBK -*-
#==========================
#The work with a picture!
#The MIT License
#Emal:ghostwwl@gmail.com
# edit by Ghostwwl
#==========================
import Image
import ImageDraw
import ImageFont
from math import atan, degrees
from os import path
import os
import sys
class MyImage:
def __init__(self, imfile = None):
if imfile:
self.filename, self.ext = path.splitext(imfile)
self.Image = Image.open(imfile)
def Rotate(self, degrees = 0):
self.Image = self.Image.rotate(degrees)
s = raw_input("是否保存:")
if "y" in s or "Y" in s:
self.Image.save(self.filename+"_Rotate.jpg")
def Show(self):
self.Image.show()
def CreateThumbnail(self, size = (128,128)):
try:
self.Image.thumbnail(size)
self.Image.save(self.filename+"_Thum.jpg", "JPEG")
print "缩略图文件保存在: %s" % (self.filename+"_Thum.jpg",)
except IOError:
sys.exit("创建缩略图失败!")
def GetSize(self):
return self.Image.size
def Save(self):
try:
self.Image.save(self.filename+"_Worked.jpg","JPEG")
except IOError:
sys.exit("保存失败!")
def WaterMark(self,text):
img = self.Image.convert("RGB")
watermark = Image.new("RGBA", img.size)
Draw = ImageDraw.ImageDraw(watermark, "RGBA")
size = 0
while True:
size += 1
font = ImageFont.truetype("c:\\windows\\Fonts\\simsun.ttc", size)
twidth, theight = font.getsize(text)
if twidth + theight/3 > watermark.size[0]:
break
Font = font
TextWidth, TextHeight = twidth, theight
Draw.setfont(Font)
Draw.text(((watermark.size[0]-TextWidth)/2, (watermark.size[1]-TextHeight)/2), unicode(text,"GBK"))
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.save(self.filename+"_Text.jpg")
def main():
while True:
ImageFile = raw_input("\n请输入图像文件:")
if path.exists(ImageFile):
Img = MyImage(ImageFile)
break
else:
print "\n请确保你输入的文件存在!"
print """
======================================================
图像旋转输入 rotate
创建缩略图输入 create
图像显示输入 show
图像加水印输入 mark
======================================================
"""
while True:
n = raw_input("请选择:")
if n in ("rotate","create","show","mark"):
break
if n == "rotate" :
degrees = int(raw_input("\n请输入旋转的角度:"))
Img.Rotate(degrees)
elif n == "create":
strSize = raw_input("请输入缩略图大小(如:128,128):").split(',')
Size = (int(strSize[0]),int(strSize[1]))
Img.CreateThumbnail(Size)
elif n == "show":
Img.Show()
else:
WaterText = raw_input("请输入水印文字:")
Img.WaterMark(WaterText)
os.system("pause")
if __name__=="__main__":
main()