python实现批量修改图片格式和尺寸


Posted in Python onJune 07, 2018

本文实例为大家分享了python批量处理图片的具体代码,供大家参考,具体内容如下

公司的一个项目要求把所有4096x4096的图片全部转化成2048x2048的图片,这种批量转换图片大小的软件网上很多,我的同事原来使用的美图看看的批量转换,但是稍微有点麻烦,每次还需要指定要转换的图片的输入路径和输出路径,而且每次都只能处理一个文件夹,很繁琐,于是我想到了万能的Python,然后写了一个脚本来批量处理图片,同一个根目录下的所有文件夹的子文件等的图片全部会处理掉。

代码中还加入了很多的异常捕获机制和提示,希望对大家有帮助。

备注:

1.导入了PIL库,是处理图片用的,很强大;

2.导入了win32库,是判断隐藏文件用的,我们的项目需要删除隐藏文件,不需要的可以直接找到删除。

3.导入send2trash库,是把删除的文件放进垃圾箱,而不是永久删除,这个我只是防止删除有用的文件而搞得,有点严谨了是吧,不需要的可以删掉啊。

4.我这个脚本是Python2.7编写的,但是在处理中文编码的时候非常恶心,尽管最后被我解决了,这个解决的方法,我随后会再单独写一篇,但是此刻我是建议大家不要用2.x版本的python 了。据说3.x的版本的已经解决了编码的问题。希望大家听我的建议。

#coding=utf-8 
import sys 
import os, glob 
import platform 
import win32file,win32con 
from PIL import Image 
from send2trash import send2trash 
 
reload(sys) 
sys.setdefaultencoding('utf-8') 
 
#new_width =2048 
#width =int(raw_input("the width U want:")) 
#imgslist = glob.glob(path+'/*.*') 
 
ShuiPing="水平" 
ShiZhuang="矢状" 
GuanZhuang="冠状" 
 
def Py_Log(_string): 
  print "----"+_string.decode('utf-8')+"----" 
 
def is_windows_system(): 
  return 'Windows' in platform.system() 
 
def is_hiden_file(file_Path):  
  if is_windows_system():  
    fileAttr = win32file.GetFileAttributes(file_Path) 
    if fileAttr & win32con.FILE_ATTRIBUTE_HIDDEN :  
      return True  
    return False  
  return False 
 
def remove_hidden_file(file_path): 
  send2trash(file_path) 
  print "Delete hidden file path:"+file_path 
 
def astrcmp(str1,str2): 
  return str1.lower()==str2.lower() 
 
def resize_image(img_path): 
  try: 
    mPath, ext = os.path.splitext(img_path) 
    if (astrcmp(ext,".png") or astrcmp(ext,".jpg")): 
      img = Image.open(img_path) 
      (width,height) = img.size 
       
      if(width != new_width): 
        new_height = int(height * new_width / width) 
        out = img.resize((new_width,new_height),Image.ANTIALIAS) 
        new_file_name = '%s%s' %(mPath,ext) 
        out.save(new_file_name,quality=100) 
        Py_Log("图片尺寸修改为:"+str(new_width)) 
      else: 
        Py_Log("图片尺寸正确,未修改") 
    else: 
      Py_Log("非图片格式") 
  except Exception,e: 
    print e 
 
#改变图片类型 
def change_img_type(img_path): 
  try: 
    img = Image.open(img_path) 
    img.save('new_type.png') 
  except Exception,e: 
    print e 
 
#处理远程图片 
def handle_remote_img(img_url): 
  try: 
    request = urllib2.Request(img_url) 
    img_data = urllib2.urlopen(request).read() 
    img_buffer = StringIO.StringIO(img_data) 
    img = Image.open(img_buffer) 
    img.save('remote.jpg') 
    (width,height) = img.size 
    out = img.resize((200,height * 200 / width),Image.ANTIALIAS) 
    out.save('remote_small.jpg') 
  except Exception,e: 
    print e 
 
def rename_forder(forder_path): 
  Py_Log("------------rename_forder--------------------------") 
  names = os.path.split(forder_path) 
  try: 
    if(unicode(ShuiPing) in unicode(names[1],'gbk')): 
      os.rename(forder_path,names[0]+"\\"+"01") 
      Py_Log(names[1]+"-->"+"01") 
    if(unicode(ShiZhuang) in unicode(names[1],'gbk')): 
      os.rename(forder_path,names[0]+"\\"+"02") 
      Py_Log(names[1]+"-->"+"02") 
    if(unicode(GuanZhuang) in unicode(names[1],'gbk')): 
      os.rename(forder_path,names[0]+"\\"+"03") 
      Py_Log(names[1]+"-->"+"03") 
  except Exception,e: 
    print e 
 
def BFS_Dir(dirPath, dirCallback = None, fileCallback = None): 
  queue = [] 
  ret = [] 
  queue.append(dirPath); 
  while len(queue) > 0: 
    tmp = queue.pop(0) 
    if(os.path.isdir(tmp)): 
      ret.append(tmp) 
      for item in os.listdir(tmp): 
        queue.append(os.path.join(tmp, item)) 
      if dirCallback: 
        dirCallback(tmp) 
    elif(os.path.isfile(tmp)): 
      ret.append(tmp) 
      if fileCallback: 
        fileCallback(tmp) 
  return ret 
 
def DFS_Dir(dirPath, dirCallback = None, fileCallback = None): 
  stack = [] 
  ret = [] 
  stack.append(dirPath); 
  while len(stack) > 0: 
    tmp = stack.pop(len(stack) - 1) 
    if(os.path.isdir(tmp)): 
      ret.append(tmp) 
      for item in os.listdir(tmp): 
        stack.append(os.path.join(tmp, item)) 
      if dirCallback: 
        dirCallback(tmp) 
    elif(os.path.isfile(tmp)): 
      ret.append(tmp) 
      if fileCallback: 
        fileCallback(tmp) 
  return ret 
 
def printDir(dirPath): 
  print "dir: " + dirPath 
  if(is_hiden_file(dirPath)): 
    remove_hidden_file(dirPath) 
  else: 
    rename_forder(dirPath) 
 
def printFile(dirPath): 
  print "file: " + dirPath 
  resize_image(dirPath) 
  return True 
 
 
if __name__ == '__main__': 
  while True: 
    path = raw_input("Path:") 
    new_width =int(raw_input("the width U want:")) 
    try: 
      b = BFS_Dir(path , printDir, printFile) 
      Py_Log ("\r\n   **********\r\n"+"*********图片处理完毕*********"+"\r\n  **********\r\n") 
    except: 
      print "Unexpected error:", sys.exc_info() 
    raw_input('press enter key to rehandle')

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

Python 相关文章推荐
跟老齐学Python之从if开始语句的征程
Sep 14 Python
在Linux下使用Python的matplotlib绘制数据图的教程
Jun 11 Python
详解Python编程中对Monkey Patch猴子补丁开发方式的运用
May 27 Python
Python使用迭代器捕获Generator返回值的方法
Apr 05 Python
python使用fcntl模块实现程序加锁功能示例
Jun 23 Python
Windows 安装 Anaconda3+PyCharm的方法步骤
Jun 13 Python
python实现批量nii文件转换为png图像
Jul 18 Python
python实现二分类的卡方分箱示例
Nov 22 Python
使用 PyTorch 实现 MLP 并在 MNIST 数据集上验证方式
Jan 08 Python
用于ETL的Python数据转换工具详解
Jul 21 Python
python实现网页录音效果
Oct 26 Python
python“静态”变量、实例变量与本地变量的声明示例
Nov 13 Python
python实现批量图片格式转换
Jun 16 #Python
python脚本实现验证码识别
Jun 07 #Python
python 创建一个空dataframe 然后添加行数据的实例
Jun 07 #Python
使用Python处理Excel表格的简单方法
Jun 07 #Python
python实现验证码识别功能
Jun 07 #Python
通过Pandas读取大文件的实例
Jun 07 #Python
Pandas:DataFrame对象的基础操作方法
Jun 07 #Python
You might like
php的memcache类分享(memcache队列)
2014/03/26 PHP
destoon实现调用热门关键字的方法
2014/07/15 PHP
PHP 实现类似js中alert() 提示框
2015/03/18 PHP
php生成图片验证码的实例讲解
2015/08/03 PHP
javascript高级学习笔记整理
2011/08/14 Javascript
JavaScript从数组中删除指定值元素的方法
2015/03/18 Javascript
基于jQuery实现在线选座之高铁版
2015/08/24 Javascript
常用的Javascript设计模式小结
2015/12/09 Javascript
javascript实现一个简单的弹出窗
2016/02/22 Javascript
AngularJS 单元测试(二)详解
2016/09/21 Javascript
Bootstrap基本组件学习笔记之进度条(15)
2016/12/08 Javascript
快速掌握jQuery插件开发
2017/01/19 Javascript
ES6中Proxy与Reflect实现重载(overload)的方法
2017/03/30 Javascript
Angular4实现动态添加删除表单输入框功能
2017/08/11 Javascript
基于jQuery实现无缝轮播与左右点击效果
2018/05/13 jQuery
vee-validate vue 2.0自定义表单验证的实例
2018/08/28 Javascript
前后端常见的几种鉴权方式(小结)
2019/08/04 Javascript
解决vue使用vant下拉框van-dropdown-item 绑定title值不变问题
2020/08/05 Javascript
echarts浮动显示单位的实现方法示例
2020/12/04 Javascript
[04:49]2014DOTA2国际邀请赛 Newbee顺利挺进总决赛 ImbaTV独家专访
2014/07/19 DOTA
[03:55]TI9战队采访——TNC Predator
2019/08/22 DOTA
Python求导数的方法
2015/05/09 Python
详解在Python中处理异常的教程
2015/05/24 Python
浅析Python装饰器以及装饰器模式
2018/05/28 Python
Python爬虫之网页图片抓取的方法
2018/07/16 Python
利用python实现.dcm格式图像转为.jpg格式
2020/01/13 Python
pycharm部署、配置anaconda环境的教程
2020/03/24 Python
利用python制作拼图小游戏的全过程
2020/12/04 Python
pycharm 配置svn的图文教程(手把手教你)
2021/01/15 Python
WoolOvers爱尔兰:羊绒、羊毛和棉针织品
2017/01/04 全球购物
意大利在线购买隐形眼镜网站:VisionDirect.it
2019/03/18 全球购物
医护人员英文求职信范文
2013/11/26 职场文书
网吧收银员岗位职责
2013/12/14 职场文书
优秀教师感人事迹材料
2014/05/04 职场文书
2014领导班子四风问题查摆思想汇报
2014/09/13 职场文书
职场领导同事生日简短祝福语
2019/08/06 职场文书