python之pyqt5-第一个pyqt5程序-图像压缩工具(2.0版本)-小记
生活随笔
收集整理的這篇文章主要介紹了
python之pyqt5-第一个pyqt5程序-图像压缩工具(2.0版本)-小记
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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 圖標(biāo)資源可不要 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('圖像壓縮工具')#圖標(biāo)#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信號與槽函數(shù)綁定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()用來進(jìn)行模糊查詢,增加參數(shù)recursive=True后可以使用**/來匹配所有子目錄files = glob( path + "**/*.JPG", recursive=True) + glob(path + "**/*.jpg", recursive=True)total = len(files) #總文件數(shù)cur = 1 #當(dāng)前文件序號for infile in files:try:print("進(jìn)度:" + 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() # 把圖片轉(zhuǎn)換成bytes流imBytes = zlib.compress(imBytes, 9) # 對圖像字節(jié)串進(jìn)行壓縮,第二個參數(shù)是壓縮率有-1,0-9,按個人情況進(jìn)行設(shè)置,我都試過了感覺沒多大變化,所以隨便設(shè)置了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()用來進(jìn)行模糊查詢,增加參數(shù)recursive=True后可以使用**/來匹配所有子目錄files = glob( path + "**/*.JPG", recursive=True) + glob(path + "**/*.jpg", recursive=True)total = len(files) #總文件數(shù)print(total)cur = 1 #當(dāng)前文件序號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以上超大圖片壓縮,如需要進(jìn)一步壓縮,可再進(jìn)行有損壓縮。"))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 藍(lán)皮阿五 閱讀(...) 評論(...) 編輯 收藏轉(zhuǎn)載于:https://www.cnblogs.com/lanpiawu/p/11209044.html
總結(jié)
以上是生活随笔為你收集整理的python之pyqt5-第一个pyqt5程序-图像压缩工具(2.0版本)-小记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bootstrap-select控件全选
- 下一篇: 算法与数据结构基础 - 堆(Heap)和