Python学习笔记(十八)PIL图像处理和Tkinter图形界面

参考资料:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/00140767171357714f87a053a824ffd811d98a83b58ec13000

https://www.cnblogs.com/xianyue/p/6588869.html

https://blog.csdn.net/tianxiawuzhei/article/details/44922843

https://blog.csdn.net/sinat_25704999/article/details/50118465

1、除了内建的模块外,Python还有大量的第三方模块。基本上,所有的第三方模块都会在PyPI - the Python Package Index上注册,只要找到对应的模块名字,即可用easy_install或者pip安装。

2、PIL是常用的第三方模块之一,全称Python Imaging Library,已经是Python平台事实上的图像处理标准库了。Window系统下使用PIL前需要作如下准备工作:

(1)从官网下载PIL安装包:http://pythonware.com/products/pil/
(2)安装时会提示在注册表中找不到Python2.7,可运行下面的python程序将Python2.7安装信息写入注册表。

#  
# script to register Python 2.0 or later for use with win32all  
# and other extensions that require Python registry settings  
#  
# written by Joakim Loew for Secret Labs AB / PythonWare  
#  
# source:  
# http://www.pythonware.com/products/works/articles/regpy20.htm  
#  
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/[email protected]/msg10512.html  
   
import sys  
   
from _winreg import *  
   
# tweak as necessary  
version = sys.version[:3]  
installpath = sys.prefix  
   
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)  
installkey = "InstallPath"  
pythonkey = "PythonPath"  
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (  
    installpath, installpath, installpath  
)  
   
def RegisterPy():  
    try:  
        reg = OpenKey(HKEY_CURRENT_USER, regpath)  
    except EnvironmentError as e:  
        try:  
            reg = CreateKey(HKEY_CURRENT_USER, regpath)  
            SetValue(reg, installkey, REG_SZ, installpath)  
            SetValue(reg, pythonkey, REG_SZ, pythonpath)  
            CloseKey(reg)  
        except:  
            print "*** Unable to register!"  
            return  
        print "--- Python", version, "is now registered!"  
        return  
    if (QueryValue(reg, installkey) == installpath and  
        QueryValue(reg, pythonkey) == pythonpath):  
        CloseKey(reg)  
        print "=== Python", version, "is already registered!"  
        return  
    CloseKey(reg)  
    print "*** Unable to register!"  
    print "*** You probably have another Python installation!"  
   
if __name__ == "__main__":  
    RegisterPy() 

注:上述代码参考自参考资料2。

(3)从https://pypi.python.org/pypi/Pillow/2.1.0#id2 下载安装 Pillow-2.1.0.win-amd64-py2.7.exe (md5) 64位版本,否则运行PIL相关代码时,会提示"The _imaging C module is not installed"。详细说明参见参考资料3。

下面是我的学习代码:

from PIL import Image, ImageFilter, ImageDraw, ImageFont
import os, random


def getNewFilename(src, mark, ext):
    result = None
    try:
        o = os.path.splitext(src)
        result = o[0] + mark + ext
    except BaseException, e:
        result = None
    return result

#生成缩略图
def createThumbnail(src):
    result = None
    try:
        im = Image.open(src)
        w, h = im.size
        im.thumbnail((w // 2, h // 2))
        result = getNewFilename(src, '_thumb', '.jpg')
        im.save(result, 'jpeg')
    except BaseException, e:
        result = None
    return result

#模糊效果
def createBlur(src):
    result = None
    try:
        im = Image.open(src)
        im2 = im.filter(ImageFilter.BLUR)
        result = getNewFilename(src, '_blur', '.jpg')
        im2.save(result, 'jpeg')
    except BaseException, e:
        result = None
    return result

# 随机字母:
def rndChar():
    return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

#创建验证码图片 w-单个验证码宽度 h-高度 count-验证码个数
def createCode(w, h, count):
    result = None
    width = w * count
    height = h
    try:
        image = Image.new('RGB', (width, height), (255, 255, 255))
        # 创建Font对象:
        font = ImageFont.truetype('C:\\Windows\\Fonts\\Arial.ttf', 36)
        # 创建Draw对象:
        draw = ImageDraw.Draw(image)
        # 填充每个像素:
        for x in range(width):
            for y in range(height):
                draw.point((x, y), fill=rndColor())
        # 输出文字:
        sCode = ''
        for t in range(count):
            c = rndChar()
            sCode = sCode + c
            draw.text((w * t + 10, 10), c, font = font, fill = rndColor2())
        # 模糊:
        image = image.filter(ImageFilter.BLUR)
        result = getNewFilename('code.jpg', '_' + sCode, '.jpg')
        image.save(result, 'jpeg')
    except BaseException, e:
        result = None
    return result

def Test():
    s = raw_input('input an image filename:')
    thumfile = createThumbnail(s)
    if thumfile != None:
        print 'thumbnail filename is %s for %s' % (thumfile, s)
    else:
        print 'createThumbnail called failure'
    blurfile = createBlur(s)
    if blurfile != None:
        print 'BLUR filename is %s for %s' % (blurfile, s)
    else:
        print 'createBlur called failure'
    codefile = createCode(60, 60, 4)
    if codefile != None:
        print 'Code Filename is %s' % codefile
    else:
        print 'createCode called failure'

注:引用PIL相关模块时,必须以“from PIL import ...”的格式,否则会提示"IOError: cannot identify image file"。详细说明参见参考资料4。

3、Python支持多种图形界面的第三方库,包括:Tk、wxWidgets、Qt、GTK等等。但是Python自带的库是支持Tk的Tkinter,使用Tkinter,无需安装任何包,就可以直接使用。直接看代码:

from Tkinter import *

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.helloLabel = Label(self, text='Hello, world!')
        self.helloLabel.pack()
        self.quitButton = Button(self, text='Quit', command=self.quit)
        self.quitButton.pack()

def Test():
    app = Application()
    # 设置窗口标题:
    app.master.title('Hello World')
    # 主消息循环:
    app.mainloop()
    return 0
今天就学习到这里,下一节从网络编程学起。

猜你喜欢

转载自blog.csdn.net/alvin_2005/article/details/80532677
今日推荐