当前位置: 移动技术网 > IT编程>脚本编程>Python > python实现批量修改图片格式和尺寸

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

2018年08月19日  | 移动技术网IT编程  | 我要评论

国庆节小报内容,幼儿园小班育儿知识大全,九州牧云录好看吗

本文实例为大家分享了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') 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网