(如想转载,请联系博主或贴上本博地址)
题外:关于python的多线程
python因为GIL的原因,只能利用到单核CPU性能。如程序内多是计算或循环,多线程无啥意义;如程序内多IO操作,多线程可以避免GUI界面无响应,因为上篇程序多IO操作,在此基础上给GUI程序加上多线程与进度条。
题内:
在上篇基础上加入2个功能。
①在初识PYQT5的基础上,本篇采用QThread实现多线程。
②给button加上drop,实现按钮接受文件拖拽。
效果如图:
下面放入代码:
主要就是在上篇基础上增加2个类,实现UI和逻辑分开。因为过于简单就不过多说明了。
①读写图片的IO线程类:
class Runthreadpic(QtCore.QThread): # 通过类成员对象定义信号对象 rsignal = pyqtSignal(str) def __init__(self): super(Runthreadpic, self).__init__() self.flag = 1 def __del__(self): self.wait() def stop(self): self.flag=0 pass def run(self): if self.flag==1: global usedtime4 try: path=pic[0].replace(r'/',r'\\') #size = (1024,600) # 定义要调整成为的尺寸(PIL会自动根据原始图片的长宽比来缩放适应设置的尺寸) try: start=time.time() img = Image.open(path) # 打开图片文件 if img.width>5: width=img.width height=img.height size=(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"保存成与原文件名一致的文件,会自动覆盖源文件 #信号传给进度条100%了 self.rsignal.emit(str(int(100))) else: pass except Exception as e: print(e) end=time.time() #耗时 usedtime4=(format(float(end-start),'.2f')) self.stop() except Exception as e: print(e)
②给button按钮增加文件拖拽到按钮功能
class Button(QPushButton): def __init__(self, title, parent): super().__init__(title, parent) self.setAcceptDrops(True) droppath=str(23) def dragEnterEvent(self, event): global droppath try: droppath=event.mimeData().text() droppath=str(droppath.replace(r'file:///',r'')).replace(r'/',r'\\') #print(droppath) f=os.path.splitext(droppath) if f[1]=='.jpg' or f[1]=='.jpeg' or f[1]=='.JPG' or f[1]=='.JPEG' or f[1]=='.png' or f[1]=='.PNG' or f[1]=='.bmp' or f[1]=='.BMP': #鼠标放开函数事件 event.accept() else: QMessageBox.information(self,"无效文件", "不是有效的图片文件!",QMessageBox.Yes) except Excetion as e: print(e) # 鼠标放开执行 def dropEvent(self, evn): try: start=time.time() im = Image.open(droppath) # 打开图片 imBytes = im.tobytes() # 把图片转换成bytes流 imBytes = zlib.compress(imBytes, 9) # 对图像字节串进行压缩,第二个参数是压缩率有-1,0-9. if im.mode == 'RGBA': im2 = Image.frombytes('RGBA',im.size, zlib.decompress(imBytes)) # 压缩成新的图片 else: im2 = Image.frombytes('RGB',im.size, zlib.decompress(imBytes)) f=os.path.splitext(droppath) newname=f[0] + '-已压缩' newname=newname+f[1] im2.save(newname) end=time.time() dropusedtime=(format(float(end-start),'.2f')) QMessageBox.information(self,"已完成", "已成功压缩图片到原有目录"+'\n'+'共耗时:'+dropusedtime+'秒',QMessageBox.Yes) except Exception as e: print(e) def dragMoveEvent(self,evn): pass