【脚本语言系列】关于Python图像处理PIL,你需要知道的事

脚本语言 专栏收录该内容
129 篇文章 0 订阅

如何使用PIL

  • 转换图片格式
# -*- coding:utf-8 -*-
#
import os
from PIL import  Image # import Image
import Tkinter
import tkFileDialog
import tkMessageBox
class Window:
    def __init__(self):
        self.root = root = Tkinter.Tk()
        label = Tkinter.Label(root, text ='选择目录')
        label.place(x = 5, y = 5)
        self.entry = Tkinter.Entry(root)
        self.entry.place(x = 55, y = 5)
        self.buttonBrowser = Tkinter.Button(root, text = '浏览', command = self.Browser)
        self.buttonBrowser.place(x = 200, y = 5)
        frameF = Tkinter.Frame(root)
        frameF.place(x =   5, y = 30)
        frameT = Tkinter.Frame(root)
        frameT.place(x = 100, y = 30)
        self.fImage = Tkinter.StringVar()
        self.tImage = Tkinter.StringVar()
        self.status = Tkinter.StringVar()
        self.fImage.set('.bmp')
        self.tImage.set('.bmp')
        labelFrom = Tkinter.Label(frameF, text = 'From')
        labelFrom.pack(anchor = 'w')
        labelTo = Tkinter.Label(frameT, text = 'To')
        labelTo.pack(anchor='w')
        frBmp = Tkinter.Radiobutton(frameF, variable = self.fImage, value = '.bmp', text = 'BMP')
        frBmp.pack(anchor='w')
        frJpg = Tkinter.Radiobutton(frameF, variable = self.fImage, value = '.jpg', text = 'JPG')
        frJpg.pack(anchor='w')
        frGif = Tkinter.Radiobutton(frameF, variable = self.fImage, value = '.gif', text = 'GIF')
        frGif.pack(anchor='w')
        frPng = Tkinter.Radiobutton(frameF, variable = self.fImage, value = '.png', text = 'PNG')
        frPng.pack(anchor='w') 
        trBmp = Tkinter.Radiobutton(frameT, variable = self.tImage, value = '.bmp', text = 'BMP')
        trBmp.pack(anchor='w')
        trJpg = Tkinter.Radiobutton(frameT, variable = self.tImage, value = '.jpg', text = 'JPG')
        trJpg.pack(anchor='w')
        trGif = Tkinter.Radiobutton(frameT, variable = self.tImage, value = '.gif', text = 'GIF')
        trGif.pack(anchor='w')
        trPng = Tkinter.Radiobutton(frameT, variable = self.tImage, value = '.png', text = 'PNG')
        trPng.pack(anchor='w')   
        self.buttonConv = Tkinter.Button(root, text ='Conv', command = self.Conv)
        self.buttonConv.place(x = 100, y = 150)
        self.labelStatus = Tkinter.Label(root, textvariable = self.status)
        self.labelStatus.place(x = 50, y = 175)
    def MainLoop(self):
        self.root.minsize(250, 200)
        self.root.maxsize(250, 200)
        self.root.mainloop()
    def Browser(self):
        directory = tkFileDialog.askdirectory(title='Python')
        if directory:
            self.entry.delete(0, Tkinter.END)
            self.entry.insert(Tkinter.END, directory)
    def Conv(self):
        n = 0
        t = self.tImage.get()
        f = self.fImage.get()
        path = self.entry.get()
        if path == '':
            tkMessageBox.showerror('Python Tkinter', 'Please input path')
            return
        filenames = os.listdir(path)
        os.mkdir(path+'/'+t[-3:])
        for filename in filenames:
            if filename[-4:] == f:
                Image.open(path + '/' + filename).save(path + '/' + t[-3:]+'/'+filename[:-4] +t)
                n = n+1
        self.status.set('successfully convert %d images' % n)
window = Window()
window.MainLoop()
  1. 选取目录
    这里写图片描述
    这里写图片描述
  2. 配置选项
    这里写图片描述
    这里写图片描述
  3. 输出图片
    这里写图片描述
    这里写图片描述

    • 生成缩略图
# -*- coding:utf-8 -*-
#
import os
from PIL import  Image # import Image
import Tkinter
import tkFileDialog
import tkMessageBox
class Window:
    def __init__(self):
        self.root = root = Tkinter.Tk()
        self.Image = Tkinter.StringVar()
        self.status = Tkinter.StringVar()
        self.mstatus = Tkinter.IntVar()
        self.fstatus = Tkinter.IntVar()
        self.Image.set('bmp')
        self.mstatus.set(0)
        self.fstatus.set(0)
        label = Tkinter.Label(root, text = 'Input Percent')
        label.place(x = 5, y = 5)
        self.entryNew = Tkinter.Entry(root)
        self.entryNew.place(x = 65, y = 5)
        self.checkM = Tkinter.Checkbutton(root, text = 'Bat Conv', command = self.OnCheckM, variable = self.mstatus, onvalue = 1, offvalue=0)
        self.checkM.place(x = 5, y = 30)
        label = Tkinter.Label(root, text = 'Choose Files')
        label.place(x = 5, y = 55)
        self.entryFile = Tkinter.Entry(root)
        self.entryFile.place(x = 55, y = 55)
        self.buttonBrowserFile = Tkinter.Button(root, text = 'Browser', command = self.BrowserFile)
        self.buttonBrowserFile.place(x = 200, y = 55)
        label = Tkinter.Entry(root, state = Tkinter.DISABLED)
        label.place(x = 5, y = 80)
        self.entryDir = Tkinter.Entry(root, state = Tkinter.DISABLED)
        self.entryDir.place(x = 55, y = 80)
        self.buttonBrowserDir = Tkinter.Button(root, text ='Browser', command = self.BrowserDir, state = Tkinter.DISABLED)
        self.buttonBrowserDir.place(x = 200, y = 80)
        self.checkF = Tkinter.Checkbutton(root, text = 'Change File Format', command = self.OnCheckF, variable = self.fstatus, onvalue=1, offvalue = 0)
        self.checkF.place(x = 5, y = 110)
        frame = Tkinter.Frame(root)
        frame.place(x = 10, y = 130)
        labelTo = Tkinter.Label(frame, text = 'Format')
        labelTo.pack(anchor='w')
        self.rBmp = Tkinter.Radiobutton(frame, variable = self.Image, value = 'bmp', text = 'BMP', state = Tkinter.DISABLED)
        self.rBmp.pack(anchor='w')
        self.rJpg = Tkinter.Radiobutton(frame, variable = self.Image, value = 'jpg', text = 'JPG', state = Tkinter.DISABLED)
        self.rJpg.pack(anchor='w')
        self.rGif = Tkinter.Radiobutton(frame, variable = self.Image, value = 'gif', text = 'GIF', state = Tkinter.DISABLED)
        self.rGif.pack(anchor='w')
        self.rPng = Tkinter.Radiobutton(frame, variable = self.Image, value = 'png', text = 'PNG', state = Tkinter.DISABLED)
        self.rPng.pack(anchor='w') 
        self.buttonConv = Tkinter.Button(root, text = 'Conv', command = self.Conv)
        self.buttonConv.place(x = 100, y = 175)
        self.labelStatus = Tkinter.Label(root, textvariable = self.status)
        self.labelStatus.place(x = 80, y = 205)
    def MainLoop(self):
        self.root.minsize(250, 250)
        self.root.minsize(250, 250)
        self.root.mainloop()
    def BrowserDir(self):
        directory = tkFileDialog.askdirectory(title='Python')
        if directory:
            self.entryDir.delete(0, Tkinter.END)
            self.entryDir.insert(Tkinter.END, directory)
    def BrowserFile(self):
        file = tkFileDialog.askopenfilename(title='Python Image Dealer',
            filetypes=[('JPG','*.jpg'),('BMP','*.bmp'),
            ('GIF','*.gif'),('PNG','*.png')])
        if file:
            self.entryFile.delete(0, Tkinter.END)
            self.entryFile.insert(Tkinter.END, file)
    def OnCheckM(self):
        if not self.mstatus.get():
            self.entryDir.config(state=Tkinter.DISABLED)
            self.entryFile.config(state = Tkinter.NORMAL)
            self.buttonBrowserDir.config(state=Tkinter.DISABLED)
            self.buttonBrowserFile.config(state=Tkinter.NORMAL)
        else:
            self.entryDir.config(state=Tkinter.NORMAL)
            self.entryFile.config(state = Tkinter.DISABLED)
            self.buttonBrowserDir.config(state=Tkinter.NORMAL)
            self.buttonBrowserFile.config(state=Tkinter.DISABLED)
    def OnCheckF(self):
        if not self.fstatus.get():
            self.rBmp.config(state = Tkinter.DISABLED)
            self.rJpg.config(state = Tkinter.DISABLED)
            self.rGif.config(state = Tkinter.DISABLED)
            self.rPng.config(state = Tkinter.DISABLED)    
        else:
            self.rBmp.config(state = Tkinter.NORMAL)
            self.rJpg.config(state = Tkinter.NORMAL)
            self.rGif.config(state = Tkinter.NORMAL)
            self.rPng.config(state = Tkinter.NORMAL)
    def Conv(self):
        n = 0
        if self.mstatus.get():
            path = self.entryDir.get()
            if path == "":
                tkMessageBox.showerror('Python Tkinter', 'Please input path')
                return
            filenames = os.listdir(path)
            if self.fstatus.get():
                f = self.Image.get()
                for filename in filenames:
                    if file[-3:] in ('bmp', 'jpg', 'gif', 'png'):
                        self.addlogo(path+'/'+filename, f)
                        n=n+1
            else:
                for filename in filenames:
                    if filename[-3:] in ('bmp', 'jpg', 'gif', 'png'):
                        self.addlogo(path+'/'+filename)
                        n=n+1
        else:
            file = self.entryFile.get()
            if file == "":
                tkMessageBox.showerror('Python Tkinter', 'Please select file')
                return
            if self.fstatus.get():
                f = self.Image.get()
                self.make(file, f)
                n=n+1
            else:
                self.make(file)
                n=n+1
        self.status.set('success add %d image' %n)
    def make(self, file, format = None):
        im = Image.open(file)
        mode = im.mode
        if mode not in ('L', 'RGB'):
            im = im.convert('RGB')
        width, height = im.size
        s = self.entryNew.get()
        if s == '':
            tkMessageBox.showerror('Python Tkinter', 'Please input percent')
            return
        else:
            n = int(s)
        nwidth = width * n / 100.0
        nheight = height * n / 100.0
        thumb = im.resize((nwidth,nheight),Image.ANTIALIAS)
        if format:
            im.save(file[:(len(file)-4)]+'_thumb.'+format)
        else:
            im.save(file[:(len(file)-4)]+'_thumb'+file[-4:])
window = Window()
window.MainLoop()
  1. 输入缩放参数并选取待转换的文件
    这里写图片描述
    这里写图片描述
    这里写图片描述

  2. 配置参数
    这里写图片描述

  3. 输出图片
    这里写图片描述
    这里写图片描述
    这里写图片描述

    • 为图片添加Logo
# -*- coding:utf-8 -*-
#
import os
from PIL import  Image # import Image
import Tkinter
import tkFileDialog
import tkMessageBox
class Window:
    def __init__(self):
        self.root = root = Tkinter.Tk()
        self.Image = Tkinter.StringVar()
        self.status = Tkinter.StringVar()
        self.mstatus = Tkinter.IntVar()
        self.fstatus = Tkinter.IntVar()
        self.pstatus = Tkinter.IntVar()
        self.Image.set('bmp')
        self.mstatus.set(0)
        self.fstatus.set(0)
        self.pstatus.set(0)
        label = Tkinter.Label(root, text = 'Logo')
        label.place(x = 5, y = 5)
        self.entryLogo = Tkinter.Entry(root)
        self.entryLogo.place(x = 55, y = 5)
        self.buttonBrowserLogo = Tkinter.Button(root, text = 'Browser', command = self.BrowserLogo)
        self.buttonBrowserLogo.place(x = 200, y = 5)
        self.checkM = Tkinter.Checkbutton(root, text = 'Bat Conv', command = self.OnCheckM, variable = self.mstatus, onvalue = 1, offvalue=0)
        self.checkM.place(x = 5, y = 30)
        label = Tkinter.Label(root, text = 'Choose Files')
        label.place(x = 5, y = 55)
        self.entryFile = Tkinter.Entry(root)
        self.entryFile.place(x = 55, y = 55)
        self.buttonBrowserFile = Tkinter.Button(root, text = 'Browser', command = self.BrowserFile)
        self.buttonBrowserFile.place(x = 200, y = 55)
        label = Tkinter.Entry(root, state = Tkinter.DISABLED)
        label.place(x = 5, y = 80)
        self.entryDir = Tkinter.Entry(root, state = Tkinter.DISABLED)
        self.entryDir.place(x = 55, y = 80)
        self.buttonBrowserDir = Tkinter.Button(root, text ='Browser', command = self.BrowserDir, state = Tkinter.DISABLED)
        self.buttonBrowserDir.place(x = 200, y = 80)
        self.checkF = Tkinter.Checkbutton(root, text = 'Change File Format', command = self.OnCheckF, variable = self.fstatus, onvalue=1, offvalue = 0)
        self.checkF.place(x = 5, y = 110)
        frame = Tkinter.Frame(root)
        frame.place(x = 10, y = 130)
        labelTo = Tkinter.Label(frame, text = 'Format')
        labelTo.pack(anchor='w')
        self.rBmp = Tkinter.Radiobutton(frame, variable = self.Image, value = 'bmp', text = 'BMP', state = Tkinter.DISABLED)
        self.rBmp.pack(anchor='w')
        self.rJpg = Tkinter.Radiobutton(frame, variable = self.Image, value = 'jpg', text = 'JPG', state = Tkinter.DISABLED)
        self.rJpg.pack(anchor='w')
        self.rGif = Tkinter.Radiobutton(frame, variable = self.Image, value = 'gif', text = 'GIF', state = Tkinter.DISABLED)
        self.rGif.pack(anchor='w')
        self.rPng = Tkinter.Radiobutton(frame, variable = self.Image, value = 'png', text = 'PNG', state = Tkinter.DISABLED)
        self.rPng.pack(anchor='w') 
        pframe = Tkinter.Frame(root)
        pframe.place(x = 70, y = 130)
        labelPos = Tkinter.Label(pframe, text = 'Location')
        labelPos.pack(anchor = 'w')
        self.rLT = Tkinter.Radiobutton(pframe, variable = self.pstatus, value = 0, text = 'Left Top')
        self.rLT.pack(anchor = 'w')
        self.rRT = Tkinter.Radiobutton(pframe, variable = self.pstatus, value = 1, text = 'Right Top')
        self.rRT.pack(anchor = 'w')
        self.rLB = Tkinter.Radiobutton(pframe, variable = self.pstatus, value = 2, text = 'Left bottom')
        self.rLB.pack(anchor = 'w')  
        self.rRB = Tkinter.Radiobutton(pframe, variable = self.pstatus, value = 3, text = 'Right bottom')
        self.rRB.pack(anchor = 'w')
        self.buttonAdd = Tkinter.Button(root, text = 'Add', command = self.Add)
        self.buttonAdd.place(x = 180, y = 175)
        self.labelStatus = Tkinter.Label(root, textvariable = self.status)
        self.labelStatus.place(x = 150, y = 205)
    def MainLoop(self):
        self.root.minsize(250, 250)
        self.root.minsize(250, 250)
        self.root.mainloop()
    def BrowserLogo(self):
        file = tkFileDialog.askopenfilename(title='Python Image Dealer',
            filetypes=[('JPG','*.jpg'),('BMP','*.bmp'),
            ('GIF','*.gif'),('PNG','*.png')])
        if file:
            self.entryLogo.delete(0, Tkinter.END)
            self.entryLogo.insert(Tkinter.END, file)
    def BrowserDir(self):
        directory = tkFileDialog.askdirectory(title='Python')
        if directory:
            self.entryDir.delete(0, Tkinter.END)
            self.entryDir.insert(Tkinter.END, directory)
    def BrowserFile(self):
        file = tkFileDialog.askopenfilename(title='Python Image Dealer',
            filetypes=[('JPG','*.jpg'),('BMP','*.bmp'),
            ('GIF','*.gif'),('PNG','*.png')])
        if file:
            self.entryFile.delete(0, Tkinter.END)
            self.entryFile.insert(Tkinter.END, file)
    def OnCheckM(self):
        if not self.mstatus.get():
            self.entryDir.config(state=Tkinter.DISABLED)
            self.entryFile.config(state = Tkinter.NORMAL)
            self.buttonBrowserDir.config(state=Tkinter.DISABLED)
            self.buttonBrowserFile.config(state=Tkinter.NORMAL)
        else:
            self.entryDir.config(state=Tkinter.NORMAL)
            self.entryFile.config(state = Tkinter.DISABLED)
            self.buttonBrowserDir.config(state=Tkinter.NORMAL)
            self.buttonBrowserFile.config(state=Tkinter.DISABLED)
    def OnCheckF(self):
        if not self.fstatus.get():
            self.rBmp.config(state = Tkinter.DISABLED)
            self.rJpg.config(state = Tkinter.DISABLED)
            self.rGif.config(state = Tkinter.DISABLED)
            self.rPng.config(state = Tkinter.DISABLED)    
        else:
            self.rBmp.config(state = Tkinter.NORMAL)
            self.rJpg.config(state = Tkinter.NORMAL)
            self.rGif.config(state = Tkinter.NORMAL)
            self.rPng.config(state = Tkinter.NORMAL)
    def Add(self):
        n = 0
        if self.mstatus.get():
            path = self.entryDir.get()
            if path == "":
                tkMessageBox.showerror('Python Tkinter', 'Please input path')
                return
            filenames = os.listdir(path)
            if self.fstatus.get():
                f = self.Image.get()
                for filename in filenames:
                    if file[-3:] in ('bmp', 'jpg', 'gif', 'png'):
                        self.addlogo(path+'/'+filename, f)
                        n=n+1
            else:
                for filename in filenames:
                    if filename[-3:] in ('bmp', 'jpg', 'gif', 'png'):
                        self.addlogo(path+'/'+filename)
                        n=n+1
        else:
            file = self.entryFile.get()
            if file == "":
                tkMessageBox.showerror('Python Tkinter', 'Please select file')
                return
            if self.fstatus.get():
                f = self.Image.get()
                self.addlogo(file, f)
                n=n+1
            else:
                self.addlogo(file)
                n=n+1
        self.status.set('success conv %d image' %n)
    def addlogo(self, file, format = None):
        logo = self.entryLogo.get()
        if logo == "":
            tkMessageBox.showerror('Python Tkinter', 'Please select Logo')
            return
        im = Image.open(file)
        lo = Image.open(logo)
        imwidth = im.size[0]
        imheight = im.size[1]
        lowidth = lo.size[0]
        loheight = lo.size[1]        
        pos = self.pstatus.get()
        if pos == 0:
            left = 0
            top = 0
            right = lowidth
            bottom = loheight
        elif pos == 1:
            left = imwidth -lowidth
            top = 0
            right = imwidth
            bottom = loheight
        elif pos == 2:
            left = 0
            top = imheight - loheight
            right = lowidth
            bottom = imheight
        else:
            left = imwidth-lowidth
            top = imheight-loheight
            right = imwidth
            bottom = imheight
        im.paste(lo, (left, top, right, bottom))
        if format:
            im.save(file[:(len(file)-4)]+'_thumb.'+format)
        else:
            im.save(file[:(len(file)-4)]+'_thumb'+file[-4:])
window = Window()
window.MainLoop()
  1. 选取Logo以及待处理文件
    这里写图片描述
    这里写图片描述
    这里写图片描述
    这里写图片描述
    这里写图片描述

  2. 配置选项
    这里写图片描述

  3. 输出图片
    这里写图片描述
    这里写图片描述

什么是PIL

PIL(Python Imaging Library)为Python提供了强大的图形处理的能力,并支持多种图形文件格式。通过使用PIL模块,可以使用Python对图片进行处理。PIL已经停止更新,现替换为Pillow!

  • 1
    点赞
  • 0
    评论
  • 1
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:鲸 设计师:meimeiellie 返回首页

打赏作者

Allen Moore

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值