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 Tkinter简单布局实例教程
Sep 03 Python
python 数据的清理行为实例详解
Jul 12 Python
Python基于更相减损术实现求解最大公约数的方法
Apr 04 Python
Python 实现取矩阵的部分列,保存为一个新的矩阵方法
Nov 14 Python
详解用python生成随机数的几种方法
Aug 04 Python
使用Python快乐学数学Github万星神器Manim简介
Aug 07 Python
Python 获取numpy.array索引值的实例
Dec 06 Python
详解python 降级到3.6终极解决方案
Feb 06 Python
python字符串下标与切片及使用方法
Feb 13 Python
解决启动django,浏览器显示“服务器拒绝访问”的问题
May 13 Python
详解基于python的图像Gabor变换及特征提取
Oct 26 Python
Python中相见恨晚的技巧
Apr 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中实现可以返回多个值的函数实例
2015/03/21 PHP
什么是PEAR?什么是PECL?PHP中两个容易混淆的概念解释
2015/07/01 PHP
php array_slice 取出数组中的一段序列实例
2016/11/04 PHP
php获取数据库中数据的实现方法
2017/06/01 PHP
PHP中cookie知识点学习
2018/05/06 PHP
浅谈php常用的7大框架的优缺点
2020/07/20 PHP
javascript编程起步(第六课)
2007/01/10 Javascript
JavaScript格式化数字的函数代码
2010/11/30 Javascript
快速解决FusionCharts联动的中文乱码问题
2013/12/04 Javascript
javascript继承的六大模式小结
2015/04/13 Javascript
jquery弹出遮掩层效果【附实例代码】
2016/04/28 Javascript
利用10行js代码实现上下滚动公告效果
2017/12/08 Javascript
使用vue-router beforEach实现判断用户登录跳转路由筛选功能
2018/06/25 Javascript
工作中常用到的ES6语法
2018/09/04 Javascript
koa2 用户注册、登录校验与加盐加密的实现方法
2019/07/22 Javascript
JS实现图片懒加载(lazyload)过程详解
2020/04/02 Javascript
javascript实现移动端红包雨页面
2020/06/23 Javascript
[01:22:29]真视界:2019年国际邀请赛总决赛
2020/01/29 DOTA
Python生成不重复随机值的方法
2015/05/11 Python
解决Python安装后pip不能用的问题
2018/06/12 Python
Python实现求解一元二次方程的方法示例
2018/06/20 Python
python实现定时发送qq消息
2019/01/18 Python
Python对象与引用的介绍
2019/01/24 Python
Appium+python自动化怎么查看程序所占端口号和IP
2019/06/14 Python
线程安全及Python中的GIL原理分析
2019/10/29 Python
python实现的Iou与Giou代码
2020/01/18 Python
Python的PIL库中getpixel方法的使用
2020/04/09 Python
深入了解Python enumerate和zip
2020/07/16 Python
HTML5新增form控件和表单属性实例代码详解
2019/05/15 HTML / CSS
GUESS Factory加拿大:牛仔裤、服装及配饰
2019/09/20 全球购物
创建精神文明单位实施方案
2014/03/08 职场文书
六一儿童节致辞
2015/07/31 职场文书
用Python简陋模拟n阶魔方
2021/04/17 Python
详解Nginx 被动检查服务器的存活状态
2021/10/16 Servers
Python使用mitmproxy工具监控手机 下载手机小视频
2022/04/18 Python
从原生JavaScript到React深入理解
2022/07/23 Javascript