python之pyqt5-第一个pyqt5程序-图像压缩工具(2.0版本)-小记
此篇为上一篇pyqt5图像压缩小工具改良版。因为比较简单,下面直接贴上代码。
效果图:
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'hellopyqt5.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! import os import sys import zlib #import resource 图标资源可不要 from os import path from PIL import Image from glob import glob from PyQt5.QtGui import QIcon from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QFileDialog from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QMainWindow from PyQt5.QtWidgets import QFrame from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_Form(QMainWindow):def __init__(self):super(QtWidgets.QMainWindow,self).__init__()self.setupUi(self)self.retranslateUi(self)def setupUi(self, Form):Form.setObjectName("Form")Form.resize(368, 290)Form.setFixedSize(368, 260)Form.setWindowTitle('图像压缩工具')#图标#Form.setWindowIcon(QIcon(':/1.png')) self.tabWidget = QtWidgets.QTabWidget(Form)self.tabWidget.setGeometry(QtCore.QRect(10, 10, 351, 271))self.tabWidget.setObjectName("tabWidget")self.tab = QtWidgets.QWidget()#指定显示特定tab #self.tab.setCurrentIndex(0)self.tab.setObjectName("tab")self.pushButton_4 = QtWidgets.QPushButton(self.tab)self.pushButton_4.setGeometry(QtCore.QRect(100, 120, 141, 41))self.pushButton_4.setObjectName("pushButton_4")#无损选择文件夹 self.pushButton_4.clicked.connect(self.opendicno)self.pushButton_3 = QtWidgets.QPushButton(self.tab)self.pushButton_3.setGeometry(QtCore.QRect(120, 70, 101, 41))self.pushButton_3.setObjectName("pushButton_3")#无损选择文件 self.pushButton_3.clicked.connect(self.openpicno)self.label = QtWidgets.QLabel(self.tab)self.label.setGeometry(QtCore.QRect(20, 10, 281, 51))self.label.setTextFormat(QtCore.Qt.AutoText)self.label.setWordWrap(True)self.label.setObjectName("label")self.tabWidget.addTab(self.tab, "")self.tab_2 = QtWidgets.QWidget()self.tab_2.setObjectName("tab_2")self.pushButton = QtWidgets.QPushButton(self.tab_2)self.pushButton.setGeometry(QtCore.QRect(120, 70, 101, 41))self.pushButton.setCheckable(False)self.pushButton.setObjectName("pushButton")#有损压缩打开文件 self.pushButton.clicked.connect(self.openfile)self.pushButton_2 = QtWidgets.QPushButton(self.tab_2)self.pushButton_2.setGeometry(QtCore.QRect(100, 120, 141, 41))self.pushButton_2.setCheckable(False)self.pushButton_2.setObjectName("pushButton_2")#有损压缩打开文件夹 self.pushButton_2.clicked.connect(self.opendic)#frame和radiobuttonself.frame = QtWidgets.QFrame(self.tab_2)self.frame.setGeometry(QtCore.QRect(0, 160, 341, 71))self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)self.frame.setFrameShadow(QtWidgets.QFrame.Raised)self.frame.setObjectName("frame") self.frame.setStyleSheet('background-color:#FAEBD7;')self.frame.setFrameShape(QFrame.Box)self.frame.setLineWidth(2)self.radioButton = QtWidgets.QRadioButton(self.frame)self.radioButton.setGeometry(QtCore.QRect(20, 40, 51, 16))self.radioButton.setObjectName("radioButton")self.radioButton_2 = QtWidgets.QRadioButton(self.frame)self.radioButton_2.setGeometry(QtCore.QRect(100, 40, 51, 16))self.radioButton_2.setObjectName("radioButton_2")self.radioButton_3 = QtWidgets.QRadioButton(self.frame)self.radioButton_3.setGeometry(QtCore.QRect(190, 40, 51, 16))self.radioButton_3.setObjectName("radioButton_3")self.radioButton_4 = QtWidgets.QRadioButton(self.frame)self.radioButton_4.setGeometry(QtCore.QRect(280, 40, 51, 16))self.radioButton_4.setObjectName("radioButton_4")#toggled信号与槽函数绑定self.radioButton.toggled.connect(lambda :self.btnstate(self.radioButton))self.radioButton_2.toggled.connect(lambda :self.btnstate(self.radioButton_2))self.radioButton_3.toggled.connect(lambda :self.btnstate(self.radioButton_3))self.radioButton_4.toggled.connect(lambda :self.btnstate(self.radioButton_4))#2个labelself.label_3 = QtWidgets.QLabel(self.frame)self.label_3.setGeometry(QtCore.QRect(10, 10, 81, 21))self.label_3.setObjectName("label_3")self.tabWidget.addTab(self.tab_2, "")self.label_2 = QtWidgets.QLabel(self.tab_2)self.label_2.setGeometry(QtCore.QRect(20, 10, 281, 51))self.label_2.setTextFormat(QtCore.Qt.AutoText)self.label_2.setWordWrap(True)self.label_2.setObjectName("label_2")self.tabWidget.addTab(self.tab_2, "")self.tabWidget.setCurrentIndex(0)self.retranslateUi(Form)#原来你在这里#self.tabWidget.setCurrentIndex(1) QtCore.QMetaObject.connectSlotsByName(Form)bs=float(0.8)def btnstate(self,btn):global bsif btn.text()=='0.8X':if btn.isChecked()==True:bs=float(0.8)print(bs)else:print("0.8没有被选中")if btn.text()=='0.6X':if btn.isChecked()==True:#global bsbs=float(0.6)print(bs)else:print("0.6没有被选中")if btn.text()=='0.4X':if btn.isChecked()==True:#global bsbs=float(0.4)print(bs)else:print("0.4没有被选中")if btn.text()=='0.2X':if btn.isChecked()==True:#global bsbs=float(0.2)print(bs)else:print("0.2没有被选中")def openfile(self):try:if self.radioButton.isChecked()==True or self.radioButton_2.isChecked()==True or self.radioButton_3.isChecked()==True or self.radioButton_4.isChecked()==True:filename ,filetype = QFileDialog.getOpenFileName(self,"选择文件","./","All Files (*);;Image Files (*.jpg)")if filename != '':path=filename.replace(r'/',r'\\')try:img = Image.open(path) # 打开图片文件if img.width>5:#等比例缩小width=img.widthheight=img.heightsize=(width*bs,height*bs)img.thumbnail(size, Image.ANTIALIAS) # 使用抗锯齿模式生成缩略图(压缩图片)f=os.path.splitext(path)newname=f[0] + '-已压缩'newname=newname+f[1]img.save(newname, "JPEG") # 保存成与原文件名一致的文件,会自动覆盖源文件else:print(file + "宽度小,已忽略")except Exception as e:print(e)QMessageBox.information(self,"恭喜,成功了!", "已成功压缩图片到原有目录",QMessageBox.Yes)#QMessageBox.Yes | QMessageBox.Noelse:QMessageBox.warning(self,"选择压缩比例", "请先选择压缩比例。",QMessageBox.Yes)except Exception as e:print(e)def opendic(self):try:if self.radioButton.isChecked()==True or self.radioButton_2.isChecked()==True or self.radioButton_3.isChecked()==True or self.radioButton_4.isChecked()==True:dic = QFileDialog.getExistingDirectory(self,"选择文件夹", "./")if dic != '':path=dic.replace(r'/',r'\\')# glob.glob()用来进行模糊查询,增加参数recursive=True后可以使用**/来匹配所有子目录files = glob( path + "**/*.JPG", recursive=True) + glob(path + "**/*.jpg", recursive=True)total = len(files) #总文件数cur = 1 #当前文件序号for infile in files:try:print("进度:" + str(cur) + "/" + str(total) + " " + infile)img = Image.open(infile) # 打开图片文件if img.width>5:width=img.widthheight=img.heightsize=(width*bs,height*bs)img.thumbnail(size, Image.ANTIALIAS) # 使用抗锯齿模式生成缩略图(压缩图片)f=os.path.splitext(infile)newname=f[0] + '-已压缩'newname=newname+f[1]img.save(newname, "JPEG") # infile保存成与原文件名一致的文件,会自动覆盖源文件else:print(infile + "宽度小,无需处理,已忽略")cur = cur + 1except Exception as e:print(e)QMessageBox.information(self,"恭喜,成功了!", "已成功压缩图片到原有目录",QMessageBox.Yes)else:QMessageBox.warning(self,"选择压缩比例", "请先选择压缩比例。",QMessageBox.Yes)except Exception as e:print(e)def openpicno(self):filename ,filetype = QFileDialog.getOpenFileName(self,"选择文件","./","All Files (*);;Image Files (*.jpg)")if filename != '':try:path=filename.replace(r'/',r'\\')im = Image.open(path) # 打开图片imBytes = im.tobytes() # 把图片转换成bytes流imBytes = zlib.compress(imBytes, 9) # 对图像字节串进行压缩,第二个参数是压缩率有-1,0-9,按个人情况进行设置,我都试过了感觉没多大变化,所以随便设置了5im2 = Image.frombytes('RGB', im.size, zlib.decompress(imBytes)) # 压缩成新的图片f=os.path.splitext(path)newname=f[0] + '-已压缩'newname=newname+f[1]im2.save(newname) # 保存成与原文件名一致的文件,会自动覆盖源文件QMessageBox.information(self,"恭喜,成功了!", "已成功压缩图片到原有目录",QMessageBox.Yes)except Exception as e:print(e)def opendicno(self):dic = QFileDialog.getExistingDirectory(self,"选择文件夹", "./")path=dic.replace(r'/',r'\\')if dic != '':path=dic.replace(r'/',r'\\')# glob.glob()用来进行模糊查询,增加参数recursive=True后可以使用**/来匹配所有子目录files = glob( path + "**/*.JPG", recursive=True) + glob(path + "**/*.jpg", recursive=True)total = len(files) #总文件数print(total)cur = 1 #当前文件序号for infile in files:try:im = Image.open(infile) # 打开if im.width>5:imBytes = im.tobytes()imBytes = zlib.compress(imBytes, 9)im2 = Image.frombytes('RGB', im.size, zlib.decompress(imBytes)) # 压缩成新图片#改名------------------------f=os.path.splitext(infile)newname=f[0] + '-已压缩'newname=newname+f[1]#改名------------------------im2.save(newname, "JPEG") # 保存成与原文件名一致的文件,会自动覆盖源文件else:print(infile + "宽度小于1200px,无需处理,已忽略")cur = cur + 1except Exception as e:print(e)QMessageBox.information(self,"恭喜,成功了!", "已成功压缩图片到原有目录",QMessageBox.Yes)def retranslateUi(self, Form):_translate = QtCore.QCoreApplication.translateForm.setWindowTitle(_translate("Form", "图像压缩工具"))self.pushButton_4.setText(_translate("Form", "选择文件夹"))self.pushButton_3.setText(_translate("Form", "选择文件"))self.label.setText(_translate("Form", "注:无损压缩不改变图像分辨率,仅改变DPI,适合10M以上超大图片压缩,如需要进一步压缩,可再进行有损压缩。"))self.label_2.setText(_translate("Form", "注:通过缩小图像分辨率压缩图片。请先选择合适的缩小比例。"))self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Form", "无损压缩"))self.pushButton.setText(_translate("Form", "选择文件"))self.pushButton_2.setText(_translate("Form", "选择文件夹"))self.radioButton.setText(_translate("Form", "0.8X"))self.radioButton_2.setText(_translate("Form", "0.6X"))self.radioButton_3.setText(_translate("Form", "0.4X"))self.radioButton_4.setText(_translate("Form", "0.2X"))self.label_3.setText(_translate("Form", "选择压缩比例"))self.label_3.setToolTip(_translate("Form", "<html><head/><body><p>手动指定压缩分辨率</p></body></html>"))self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Form", "有损压缩")) # self.tabWidget.setCurrentIndex(self.tabWidget.indexOf(self.tab))if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv)Form = QtWidgets.QMainWindow()ui = Ui_Form()ui.setupUi(Form)Form.show()sys.exit(app.exec_())
posted on 2019-07-18 18:03 蓝皮阿五 阅读(...) 评论(...) 编辑 收藏