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生成器的使用方法
Nov 21 Python
python通过urllib2获取带有中文参数url内容的方法
Mar 13 Python
python中partial()基础用法说明
Dec 30 Python
python实现的爬取电影下载链接功能示例
Aug 26 Python
在Python中使用MySQL--PyMySQL的基本使用方法
Nov 19 Python
wxPython之wx.DC绘制形状
Nov 19 Python
python数据库开发之MongoDB安装及Python3操作MongoDB数据库详细方法与实例
Mar 18 Python
Numpy一维线性插值函数的用法
Apr 22 Python
python属于哪种语言
Aug 16 Python
python获取本周、上周、本月、上月及本季的时间代码实例
Sep 08 Python
python 实现弹球游戏的示例代码
Nov 17 Python
在Python 中将类对象序列化为JSON
Apr 06 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中$_SERVER的详细参数与说明
2008/07/29 PHP
PHP字符串处理的10个简单方法
2010/06/30 PHP
php中的filesystem文件系统函数介绍及使用示例
2014/02/13 PHP
ThinkPHP使用Smarty第三方插件方法小结
2016/03/19 PHP
php通过两层过滤获取留言内容的方法
2016/07/11 PHP
Centos7安装swoole扩展操作示例
2020/03/26 PHP
为javascript添加String.Format方法
2020/08/11 Javascript
JQuery与iframe交互实现代码
2009/12/24 Javascript
form表单只提交数据而不进行页面跳转的解决方案
2013/09/18 Javascript
JQuery页面的表格数据的增加与分页的实现
2013/12/10 Javascript
javascript对象的使用和属性操作示例详解
2014/03/02 Javascript
javascript上下方向键控制表格行选中并高亮显示的方法
2015/02/13 Javascript
js+html5获取用户地理位置信息并在Google地图上显示的方法
2015/06/05 Javascript
jquery实现表单验证简单实例演示
2015/11/23 Javascript
JS中生成随机数的用法及相关函数
2016/01/09 Javascript
用JS实现图片轮播效果代码(一)
2016/06/26 Javascript
利用node.js+mongodb如何搭建一个简单登录注册的功能详解
2017/07/30 Javascript
vue组件 $children,$refs,$parent的使用详解
2017/07/31 Javascript
使用JS实现气泡跟随鼠标移动的动画效果
2017/09/16 Javascript
Vue 中使用vue2-highcharts实现top功能的示例
2018/03/05 Javascript
vue中改变滚动条样式的方法
2020/03/03 Javascript
Python爬虫番外篇之Cookie和Session详解
2017/12/27 Python
pandas 获取季度,月度,年度首尾日期的方法
2018/04/11 Python
对python中字典keys,values,items的使用详解
2019/02/03 Python
使用python爬取抖音app视频的实例代码
2020/12/01 Python
Mytheresa英国官网:拥有160多个奢侈品品牌
2016/10/09 全球购物
会计主管岗位职责范文
2013/11/08 职场文书
临床医学专业学生的自我评价分享
2013/11/21 职场文书
《春晓》教学反思
2014/04/20 职场文书
祖国在我心中演讲稿600字
2014/05/04 职场文书
创先争优活动心得体会
2014/09/04 职场文书
挂靠协议书
2015/01/27 职场文书
2015法院个人工作总结范文
2015/05/25 职场文书
怒海潜将观后感
2015/06/11 职场文书
2019年销售人员的职业生涯规划书
2019/03/25 职场文书
如何解决.cuda()加载用时很长的问题
2021/05/24 Python