首页 > 编程笔记

Pillow Image实现图像复制与粘贴

我们可以使用 Image 模块的 copy() 方法复该图像,使用 Image 模块的 paste() 方法粘贴图像,使用 Image 模块的 crop() 方法剪下图像中的一个矩形方块。这三个方法的语法如下:
复制图像:copy() 
粘贴图像:paste(image, box)
剪切图像一部分:crop(box)
box 该图像中的一个矩形方块,是一个含有 4 个元素的元组:(left, top, right, bottom),表示矩形左上角与右下角的坐标。如果使用的是 paste() 方法,box 就是一个含有两个元素的元组:((left, top), (right, bottom))。

下面的示例是创建使用相同图文件的左右两个图像。右边的图像是将原来图像的上半部旋转 180° 后复制粘贴到上半部的。
#复制与粘贴图像
from tkinter import *
from PIL import Image, ImageTk
#创建主窗口
win = Tk()
win. title (string ="复制与粘贴图像")
#打开图像文件
path = "D: \\python\\ch14\\"
imgFile = Image .open(path + "14.2.jpg")
#创建第一个图像实例变量
img1 = ImageTk. PhotoImage (imgFile)
#读取图像文件的宽与高
width, height = imgFile.size
#设置剪下的区块范围
box1 = (0, 0,width, int (height/2) )
#将图像的上半部剪下
part = imgFile. crop (box1)
#将图像旋转180度
part= part. transpose (Image .ROTATE_180)
#将图像的上半部粘贴到上半部
imgFile.paste (part, box1)
#创建第二个图像实例变量
img2 = ImageTk. PhotoImage (imgFile)
#创建Label控件,以显示图像
labell = Label (win, width=400,height=400,image=img1,borderwidth=l)
label2 = Label (win, width=400,height=400,image=img2,borderwidth=1)
label1.pack (side=LEFT)
label2. pack (side=LEFT)
#开始程序循环
win. mainloop()
保存并运行程序 demo1.py,结果如图 1 所示:

程序运行结果
图1:程序运行结果

优秀文章