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 04 Python
Python线程中对join方法的运用的教程
Apr 09 Python
Python中生成器和yield语句的用法详解
Apr 17 Python
在Python中操作列表之List.append()方法的使用
May 20 Python
Python3.5 处理文本txt,删除不需要的行方法
Dec 10 Python
Python基础之函数的定义与使用示例
Mar 23 Python
Python对象转换为json的方法步骤
Apr 25 Python
python生成随机红包的实例写法
Sep 02 Python
numpy.transpose()实现数组的转置例子
Dec 02 Python
python 画函数曲线示例
Dec 04 Python
python kafka 多线程消费者&手动提交实例
Dec 21 Python
使用python 的matplotlib 画轨道实例
Jan 19 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 中的str_replace 函数总结
2007/04/27 PHP
snoopy 强大的PHP采集类使用实例代码
2010/12/09 PHP
列举PHP的Yii 2框架的开发优势
2015/07/03 PHP
PHP.vs.JAVA
2016/04/29 PHP
jquery nth-child()选择器的简单应用
2010/07/10 Javascript
js报错 Object doesn't support this property or method的原因分析
2011/03/31 Javascript
自定义一个jquery插件[鼠标悬浮时候 出现说明label]
2011/06/27 Javascript
33个优秀的jQuery 教程分享(幻灯片、动画菜单)
2011/07/08 Javascript
图标线性回归斜着移动到指定的位置
2013/08/16 Javascript
jQuery基于当前元素进行下一步的遍历
2014/05/20 Javascript
jquery实现华丽的可折角广告代码
2015/09/02 Javascript
jquery实现滑屏大图定时收缩为小banner图片的广告代码
2015/09/02 Javascript
谈谈encodeURI和encodeURIComponent以及escape的区别与应用
2015/11/24 Javascript
Node.js模块封装及使用方法
2016/03/06 Javascript
微信小程序 实战小程序实例
2016/10/08 Javascript
node.js+captchapng+jsonwebtoken实现登录验证示例
2017/08/17 Javascript
Bootstrap Tooltip显示换行和左对齐的解决方案
2017/10/11 Javascript
你点的 ES6一些小技巧,请查收
2018/04/25 Javascript
bootstrap 弹出框modal添加垂直方向滚轴效果
2018/07/09 Javascript
vue.js template模板的使用(仿饿了么布局)
2018/08/13 Javascript
vue实现多级菜单效果
2019/10/19 Javascript
Vue+elementUI实现多图片上传与回显功能(含回显后继续上传或删除)
2020/03/23 Javascript
[01:04:05]VG vs Newbee 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
pycharm 取消默认的右击运行unittest的方法
2018/11/29 Python
DRF跨域后端解决之django-cors-headers的使用
2019/01/27 Python
详解Python 定时框架 Apscheduler原理及安装过程
2019/06/14 Python
Python Opencv任意形状目标检测并绘制框图
2019/07/23 Python
Python列表的切片实例讲解
2019/08/20 Python
python json.dumps中文乱码问题解决
2020/04/01 Python
Python叠加矩形框图层2种方法及效果
2020/06/18 Python
微软香港官网及网上商店:Microsoft HK
2016/09/01 全球购物
意向书范文
2014/03/31 职场文书
共筑中国梦演讲稿
2014/04/23 职场文书
省级青年文明号申报材料
2014/05/23 职场文书
如何解决php-fpm启动不了问题
2021/11/17 PHP
Golang jwt身份认证
2022/04/20 Golang