首先上代码 如果不想复制粘贴 请去下载: 链接:https://pan.baidu.com/s/1DG7beVFvQE_gW_QHz7-HYQ 提取码:mtha
import sys
from PyQt5 import QtWidgets,QtGui,QtCore,Qt
from PIL import Image
import os
class GUI(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initGUI()
def initGUI(self):
self.resize(500,500)
qr = self.frameGeometry()
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
self.setWindowTitle('图片压缩')
self.setWindowIcon(QtGui.QIcon('2.png'))
self.setToolTip('窗口提示')
self.label = QtWidgets.QLabel(self)
self.label.setGeometry(QtCore.QRect(80, 10, 330, 80))
self.label.setText('请输入图片所在路径(如:C:/Users/13509/Desktop/670.png)')
self.label.setObjectName('label')
self.label.setToolTip('label提示')
self.label1 = QtWidgets.QLabel(self)
self.label1.setGeometry(QtCore.QRect(80, 100, 330, 80))
self.label1.setText('请输入图片输出路径(如:C:/Users/13509/Desktop/670.png)')
self.label1.setObjectName('label')
self.label1.setToolTip('label提示')
self.textbox = Qt.QLineEdit(self)
self.textbox.resize(320,40)
self.textbox.move(90, 80)
self.textbox1 = Qt.QLineEdit(self)
self.textbox1.resize(320,40)
self.textbox1.move(90, 160)
self.textbox.setToolTip('输入框提示')
self.btn =QtWidgets.QPushButton('压缩图片',self)
self.btn.resize(200,40)
self.btn.move(140,220)
self.btn.setStyleSheet("background-color: #FF3333;"
"border-color: rgb(170, 150, 163);"
"font: 75 12pt \"Arial Narrow\";"
"color: rgb(126, 255, 46);")
self.btn.setToolTip('按钮提示')
self.btn.clicked.connect(self.clickbtn)
self.show();
def clickbtn(self):
oldImgae = self.textbox.text()
newImage = self.textbox1.text()
compress_image(oldImgae,newImage)
QtWidgets.QMessageBox.question(self, "信息", '压缩成功',QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
def closeEvent(self, QCloseEvent):
reply = QtWidgets.QMessageBox.question(self, '警告',"确定关闭当前窗口?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.Yes:
QCloseEvent.accept()
else:
QCloseEvent.ignore()
def get_size(file):
size = os.path.getsize(file)
return size / 1024
def get_outfile(infile, outfile):
if outfile:
return outfile
dir, suffix = os.path.splitext(infile)
outfile = '{}-out{}'.format(dir, suffix)
return outfile
def compress_image(infile, outfile='', mb=1500, step=10, quality=80):
"""不改变图片尺寸压缩到指定大小
:param infile: 压缩源文件
:param outfile: 压缩文件保存地址
:param mb: 压缩目标,KB
:param step: 每次调整的压缩比率
:param quality: 初始压缩比率
:return: 压缩文件地址,压缩文件大小
"""
o_size = get_size(infile)
if o_size <= mb:
return infile
outfile = get_outfile(infile, outfile)
while o_size > mb:
im = Image.open(infile)
im.save(outfile, quality=quality)
if quality - step < 0:
break
quality -= step
o_size = get_size(outfile)
return outfile, get_size(outfile)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
gui = GUI()
sys.exit(app.exec_())
|