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 base64 decode incorrect padding错误解决方法
Jan 08 Python
Python检测网站链接是否已存在
Apr 07 Python
python strip() 函数和 split() 函数的详解及实例
Feb 03 Python
Python实现脚本锁功能(同时只能执行一个脚本)
May 10 Python
python实现将excel文件转化成CSV格式
Mar 22 Python
python和flask中返回JSON数据的方法
Mar 26 Python
Python Xml文件添加字节属性的方法
Mar 31 Python
python pandas中DataFrame类型数据操作函数的方法
Apr 08 Python
Python并行分布式框架Celery详解
Oct 15 Python
python获取微信小程序手机号并绑定遇到的坑
Nov 19 Python
python学习——内置函数、数据结构、标准库的技巧(推荐)
Apr 18 Python
Django rstful登陆认证并检查session是否过期代码实例
Aug 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+dbfile开发小型留言本
2006/10/09 PHP
php结合表单实现一些简单功能的例子
2011/06/04 PHP
分享微信扫码支付开发遇到问题及解决方案-附Ecshop微信支付插件
2015/08/23 PHP
PHP消息队列用法实例分析
2016/02/12 PHP
详解php中的implements 使用
2017/06/13 PHP
PHP实现一个按钮点击上传多个图片操作示例
2020/01/23 PHP
原生js实现给指定元素的后面追加内容
2013/04/10 Javascript
javascript实现简单的Map示例介绍
2013/12/23 Javascript
解决window.opener=null;window.close(),只支持IE6不支持IE7,IE8的问题
2014/01/14 Javascript
node.js中的fs.readlink方法使用说明
2014/12/17 Javascript
javascript 操作符(~、&、|、^、)使用案例
2014/12/31 Javascript
JS实现可缩放、拖动、关闭和最小化的浮动窗口完整实例
2015/03/04 Javascript
纯JS代码实现一键分享功能
2016/04/20 Javascript
Node.js的npm包管理器基础使用教程
2016/05/26 Javascript
JavaScript ES5标准中新增的Array方法
2016/06/28 Javascript
JavaScript中捕获与冒泡详解及实例
2017/02/03 Javascript
jquery ajaxfileupload异步上传插件
2017/11/21 jQuery
30分钟精通React今年最劲爆的新特性——React Hooks
2019/03/11 Javascript
微信小程序云开发(数据库)详解
2019/05/17 Javascript
JavaScript函数式编程(Functional Programming)组合函数(Composition)用法分析
2019/05/22 Javascript
ES6小技巧之代替lodash
2019/06/07 Javascript
Vue监听页面刷新和关闭功能
2019/06/20 Javascript
JS事件流与事件处理程序实例分析
2019/08/16 Javascript
vue 中几种传值方法(3种)
2019/11/12 Javascript
JavaScript实现矩形块大小任意缩放
2020/08/25 Javascript
[02:18]《我与DAC》之工作人员:为了热爱DOTA2的玩家们
2018/03/28 DOTA
[48:32]VGJ.T vs Fnatic 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
使用Python多线程爬虫爬取电影天堂资源
2016/09/23 Python
Python实现通过文件路径获取文件hash值的方法
2017/04/29 Python
python机器学习理论与实战(六)支持向量机
2018/01/19 Python
Python根据欧拉角求旋转矩阵的实例
2019/01/28 Python
Atom Python 配置Python3 解释器的方法
2019/08/28 Python
python如何求圆的面积
2020/07/01 Python
Python接口自动化系列之unittest结合ddt的使用教程详解
2021/02/23 Python
用CSS3实现无限循环的无缝滚动的示例代码
2017/11/01 HTML / CSS
货代行业个人求职简历的自我评价
2013/10/22 职场文书