侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   169

本文实例为大家分享了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实现批量图片格式转换
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客