编程的步骤如下:
(1) 首先利用PyQt Designer进行界面设计,并将.ui文件转换成.py文件;
(2) 在形成的.py文件中增加第11-15行代码;增加87-91行代码;
(3) 编写相关的函数;
(4) 按21-26行的形式,将QT控件的相应的信号和槽(Python的函数)连接起来。
- # -*- coding: utf-8 -*-
- import sys
- from PyQt5 import QtCore
- from PyQt5 import QtGui
- from PyQt5 import QtWidgets
- from PyQt5.QtWidgets import QFileDialog
- from PIL import Image #导入Image模块
- from PIL import ImageEnhance #导入ImageEnhance模块
- class Ui_Form(QtWidgets.QWidget):
- #添加11-15行程序
- def __init__(self):
- super(Ui_Form,self).__init__()
- self.setupUi(self)
- self.retranslateUi(self)
- self.scale=0
- def setupUi(self, Form):
- . #略
- . #略
- . #略
- self.pushButton_open.clicked.connect(self.openimg)
- self.pushButton_large.clicked.connect(self.largeimg)
- self.pushButton_Small.clicked.connect(self.smallimg)
- self.pushButton_rotate.clicked.connect(self.rotate)
- self.pushButton_save.clicked.connect(self.save)
- self.pushButton_enhance.clicked.connect(self.enhance)
- def openimg(self,): # 打开文件函数
- fileName, filetype = QFileDialog.getOpenFileName(self,
- "选取文件",
- "C:/",
- "所有图像文件(*.jpg)")
- self.img=Image.open(fileName)
- pix=self.pil2pixmap(self.img) # 将PIL图像转换QImage格式
- self.label_img.setPixmap(pix) #在标签中显示图像
- def save(self): # 保存文件函数
- fileName,ok = QFileDialog.getSaveFileName(self,
- "文件保存",
- "C:/",
- "图像文件 (*.jpg)")
- if fileName:
- self.img.save(fileName)
- QtWidgets.QMessageBox.information(self,"信息提示","文件保存成功!!!")
- def rotate(self): # 旋转图像函数
- new_img=self.img.rotate(90)
- self.showimg(new_img)
- self.img=new_img
- def largeimg(self): #图像放大函数
- self.scale+=0.2
- new_width,newheight = self.img.size
- new_width=int(new_width*(1+self.scale))
- newheight=int(newheight*(1+self.scale))
- new_img = self.img.resize((new_width,newheight))
- self.showimg(new_img)
- def smallimg(self): #图像缩小函数
- self.scale-=0.2
- new_width,newheight = self.img.size
- new_width=int(new_width*(1+self.scale))
- newheight=int(newheight*(1+self.scale))
- new_img = self.img.resize((new_width,newheight))
- self.showimg(new_img)
- def enhance(self): #图像增强函数
- brightness = ImageEnhance.Brightness(self.img)
- bright_img = brightness.enhance(2.0) #增加图像亮度
- self.showimg(bright_img)
- self.img=bright_img
- def pil2pixmap(self,img): #图像格式转换函数
- im = img
- im = im.convert("RGBA")
- data = im.tobytes("raw","RGBA")
- qim = QtGui.QImage(data, im.size[0],
- im.size[1], QtGui.QImage.Format_ARGB32)
- pix = QtGui.QPixmap.fromImage(qim)
- return pix
- def showimg(self,img): #在QT中显示图像函数
- pix=self.pil2pixmap(img)
- self.label_newimg.clear()
- self.label_newimg.setPixmap(pix) #将PIL图像转换为QT图像
- if __name__=="__main__":
- app=QtWidgets.QApplication(sys.argv)
- ui=Ui_Form()
- ui.show()
- sys.exit(app.exec_())