python+pyqt5实现图片批量缩放工具


Posted in Python onMarch 18, 2019

批量修改图片大小好像用PS也可以,不过我不会,程序猿就用程序来解决。
这段时间学了下Python,很强大,之前一些不知道怎么处理的东西在Python里面都能找到解决方法。

工具界面如下图

python+pyqt5实现图片批量缩放工具

这个工具需要用到第三方库 Pillow 和 Pyqt5,可通过命令行安装。

pip install pillow
pip install pyqt5

代码:

#!-*-coding:utf-8-*-

from PIL import Image

import hashlib, os, sys
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtWidgets import (QFileDialog, QMessageBox,
  QGridLayout, QLineEdit, QTextEdit, QLabel, QWidget, QToolTip, 
  QPushButton, QApplication, QInputDialog)
from PyQt5.QtCore import QCoreApplication


def makedir(path):
  if not os.path.exists(path):
    os.mkdir(path)


def image_resize(image_path, scale):
  #获得新文件名称
  out_path = os.path.splitext(image_path)[0] + "_after" + os.path.splitext(image_path)[-1]
  with Image.open( image_path ) as im:
    width = int(im.size[0]*scale)
    height = int(im.size[1]*scale)
    #resize 设置新尺寸
    out = im.resize( (width, height) )
    out.save(out_path)

def folder_resize(folder_path, scale):
  dst_files = []
  files = os.listdir( folder_path )
  for file in files:
    ext = os.path.splitext(file)[-1]
    #只支持jpg或png文件
    if ext == ".jpg" or ext == ".png":
      dst_files.append(file)

  #输出路径
  out_folder = os.path.join(folder_path, "after")
  makedir(out_folder)

  for item in dst_files:
    try:
      op = os.path.join( out_folder, item )
      with Image.open( os.path.join(folder_path, item) ) as im:
        width = int(im.size[0]*scale)
        height = int(im.size[1]*scale)
        out = im.resize( (width, height) )
        out.save(op)
    except FileNotFoundError:
      print("file not found " + item)


class MainBody(QWidget):
  def __init__(self):
    super(MainBody, self).__init__()
    self.init()

    self.m_scale = 1.0
    self.m_width = 0
    self.m_height = 0

  def init(self):
    grid = QGridLayout()
    self.setLayout(grid)
    grid.setSpacing(10)

    self.m_tedit = QTextEdit()
    self.m_tedit.setToolTip( u'可以拖拽文件到这里来' )
    grid.addWidget(self.m_tedit, 1, 0, 4, 3)

    self.m_scale_set_btn = QPushButton( u"设置缩放值" )
    self.m_scale_set_btn.clicked.connect( self.set_scale_func )
    grid.addWidget( self.m_scale_set_btn, 1, 3 )
    self.m_scale_label = QLabel( "1.0" )
    grid.addWidget( self.m_scale_label, 2, 3 )

    self.m_height_set_btn = QPushButton( u"设置高度" )
    self.m_height_set_btn.clicked.connect( self.set_height_func )
    grid.addWidget( self.m_height_set_btn, 3, 3 )
    self.m_height_label = QLabel( "0" )
    grid.addWidget( self.m_height_label, 4, 3 )

    self.m_width_set_btn = QPushButton( u"设置宽度" )
    self.m_width_set_btn.clicked.connect( self.set_width_func )
    grid.addWidget( self.m_width_set_btn, 5, 3 )
    self.m_width_label = QLabel( "0" )
    grid.addWidget( self.m_width_label, 6, 3 )

    self.m_file_btn = QPushButton(u'选择文件')
    self.m_file_btn.clicked.connect( self.file_func )

    self.m_folder_btn = QPushButton(u'选择文件夹')
    self.m_folder_btn.clicked.connect( self.folder_func )

    self.m_generate_btn = QPushButton(u'处理')
    self.m_generate_btn.clicked.connect( self.generate_func )

    self.m_clear_btn = QPushButton(u'清空')
    self.m_clear_btn.clicked.connect( self.clear_func )

    grid.addWidget(self.m_file_btn, 5, 0)
    grid.addWidget(self.m_folder_btn, 5, 1)
    grid.addWidget(self.m_generate_btn, 6, 0)
    grid.addWidget(self.m_clear_btn, 6, 1)

    self.setGeometry(300,300,300,200)
    self.setWindowTitle(u"批量图片缩放")
    self.setWindowIcon(QIcon('icon.png'))
    self.show()

  #按照输入的缩放值进行缩放
  def set_scale_func(self):
    text, ok = QInputDialog.getText( self, 'Input Scale', u'输入缩放值' )
    if ok:
      try:
        scale = float( text )
      except ValueError:
        QMessageBox.warning( self, u"设置缩放值", u"输入错误" )
      else:
        self.m_scale = scale
        self.refresh_setting(0)

  #根据高度的缩放比例等比例缩放
  def set_height_func(self):
    text, ok = QInputDialog.getText( self, 'Input Height', u'输入高度' )
    if ok:
      try:
        height = int( text )
      except ValueError:
        QMessageBox.warning( self, u"设置高度", u"输入错误" )
      else:
        self.m_height = height
        self.refresh_setting(2)

  #根据宽度的缩放比例等比例缩放
  def set_width_func(self):
    text, ok = QInputDialog.getText( self, 'Input Width', u'输入宽度' )
    if ok:
      try:
        width = int( text )
      except ValueError:
        QMessageBox.warning( self, u"设置宽度", u"输入错误" )
      else:
        self.m_width = width
        self.refresh_setting(1)

  def file_func(self):
    filename, ok = QFileDialog.getOpenFileName(self, "Open File", "C:/Users/Administrator/Desktop", "JPG (*.jpg);;PNG (*.png)")
    if ok:        
      self.m_tedit.setText( filename )

      size = self.get_image_size( filename )
      s,w,h = self.get_current_setting()
      self.m_width = int(size[0]*s)
      self.m_height = int(size[1]*s)
      self.m_height_label.setText( str( self.m_height ) )
      self.m_width_label.setText( str( self.m_width ) )

  def folder_func(self):
    filename = QFileDialog.getExistingDirectory(self, "Open File", "C:/Users/Administrator/Desktop")
    self.m_tedit.setText( filename )


  def generate_func(self):
    path = self.get_image_path()
    if path == None or path == "":
      QMessageBox.warning( self, u"Error", u"未选择文件" )
      return
    elif os.path.exists(path) == False:
      QMessageBox.warning( self, u"Error", u"文件不存在" )
      return

    if os.path.isdir(path):
      folder_resize( path, self.m_scale )
    elif os.path.isfile(path):
      image_resize( path, self.m_scale )


  def clear_func(self):
    self.m_tedit.clear()
    self.m_width = 0
    self.m_height = 0
    self.m_width_label.setText("0")
    self.m_height_label.setText("0")

  def get_image_size(self, image_path):
    with Image.open(image_path) as im:
      return im.size

  def get_image_path(self):
    path = self.m_tedit.toPlainText()
    if path.startswith( 'file:///' ):
      path = path[8:]
    return path

  def get_current_setting(self):
    return self.m_scale, self.m_width, self.m_height

  def refresh_setting(self, kind):
    s, w, h = self.get_current_setting()
    p = self.get_image_path()
    if kind == 0:
      if p == None or p == "" or os.path.exists(p) == False or os.path.isdir(p) == True:
        w = 0
        h = 0
      else:
        size = self.get_image_size(p)
        w = size[0]*s
        h = size[1]*s

    elif kind == 1:
      if p == None or p == "" or os.path.exists(p) == False:
        QMessageBox.warning( self, u"Warning", u"请先选择文件" )
        return
      elif os.path.isdir(p) == True:
        QMessageBox.warning( self, u"Warning", u"文件夹不能设置宽度" )
        return

      size = self.get_image_size(p)
      w = int(w)
      s = w*1.0/size[0]
      h = int((w/size[0])*size[1])

    elif kind == 2:
      if p == None or p == "" or os.path.exists(p) == False:
        QMessageBox.warning( self, u"Warning", u"请先选择文件" )        
        return
      elif os.path.isdir(p) == True:
        QMessageBox.warning( self, u"Warning", u"文件夹不能设置高度" )
        return

      size = self.get_image_size(p)
      h = int(h)
      s = h*1.0/size[1]
      w = int((h/size[1])*size[0])

    self.m_width = int(w)
    self.m_height = int(h)
    self.m_scale = float(s)
    self.m_width_label.setText(str(self.m_width))
    self.m_height_label.setText(str(self.m_height))
    self.m_scale_label.setText(str(self.m_scale))



if __name__ == "__main__":
  app = QApplication(sys.argv)
  mb = MainBody()
  sys.exit( app.exec_() )

整个工具比较简陋,能用就好。有什么不正确的地方请指出。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中pycurl库的用法实例
Sep 30 Python
Python Tkinter GUI编程入门介绍
Mar 10 Python
在Python中操作字符串之replace()方法的使用
May 19 Python
python实现二维码扫码自动登录淘宝
Dec 27 Python
Python socket套接字实现C/S模式远程命令执行功能案例
Jul 06 Python
python中pygame安装过程(超级详细)
Aug 04 Python
Pandas DataFrame中的tuple元素遍历的实现
Oct 23 Python
在python中做正态性检验示例
Dec 09 Python
python实现简单坦克大战
Mar 27 Python
django 多数据库及分库实现方式
Apr 01 Python
python 贪心算法的实现
Sep 18 Python
Python超详细分步解析随机漫步
Mar 17 Python
Python实现从SQL型数据库读写dataframe型数据的方法【基于pandas】
Mar 18 #Python
PyQt5实现简易计算器
May 30 #Python
Python实现简单层次聚类算法以及可视化
Mar 18 #Python
PyQt5实现简单数据标注工具
Mar 18 #Python
Python简单I/O操作示例
Mar 18 #Python
python实现简单图片物体标注工具
Mar 18 #Python
Python面向对象程序设计之类的定义与继承简单示例
Mar 18 #Python
You might like
PHP 获取MSN好友列表的代码(2009-05-14测试通过)
2009/09/09 PHP
跟我学Laravel之路由
2014/10/15 PHP
php计算年龄精准到年月日
2015/11/17 PHP
thinkPHP中create方法与令牌验证实例浅析
2015/12/08 PHP
Laravel框架数据库迁移操作实例详解
2020/04/06 PHP
雄兵连第三季海报曝光,艾妮熙德成主角,蔷薇新造型
2021/03/09 国漫
用jQuery打造TabPanel效果代码
2010/05/22 Javascript
jQuery 获取对象 定位子对象
2010/05/31 Javascript
jquery 弹出层注册页面等(asp.net后台)
2010/06/17 Javascript
Jquery动态进行图片缩略的原理及实现
2013/08/13 Javascript
在父页面调用子页面的JS方法
2013/09/29 Javascript
setInterval()和setTimeout()的用法和区别示例介绍
2013/11/17 Javascript
兼容最新firefox、chrome和IE的javascript图片预览实现代码
2014/08/08 Javascript
基于dropdown.js实现的两款美观大气的二级导航菜单
2015/09/02 Javascript
基于JavaScript实现鼠标箭头移动图片跟着移动
2016/08/30 Javascript
prototype.js简单实现ajax功能示例
2017/10/18 Javascript
使用JavaScript保存文本文件到本地的两种方法
2019/01/22 Javascript
JS中封装axios来管控api的2种方式
2019/09/11 Javascript
[01:36:57]【09DOTA2第一视角】小骷髅
2014/04/16 DOTA
[01:38]完美世界DOTA2联赛(PWL)宣传片:第一站
2020/10/26 DOTA
9种python web 程序的部署方式小结
2014/06/30 Python
Python2中的raw_input() 与 input()
2015/06/12 Python
基于Python2、Python3中reload()的不同用法介绍
2019/08/12 Python
关于Pytorch的MNIST数据集的预处理详解
2020/01/10 Python
python中get和post有什么区别
2020/06/19 Python
英国奢侈品概念店:Base Blu
2019/05/16 全球购物
婚礼主持结束词
2014/03/13 职场文书
写求职信要注意什么问题
2014/04/12 职场文书
工作岗位说明书模板
2014/05/09 职场文书
工商行政管理专业求职书
2014/05/23 职场文书
甜品店创业计划书
2014/09/21 职场文书
2015年大学教师工作总结
2015/05/20 职场文书
大学文艺委员竞选稿
2015/11/19 职场文书
员工安全责任协议书
2016/03/22 职场文书
Pandas实现DataFrame的简单运算、统计与排序
2022/03/31 Python
公历12个月名称的由来
2022/04/12 杂记