python批量图片处理简单示例

系统 1583 0

本文实例讲述了python批量图片处理。分享给大家供大家参考,具体如下:

            
#!/usr/bin/python
#coding:utf-8
import os
from PIL import Image
#源目录
MyPath = 'C:/Users/Eric/Desktop/python_text/20161214/test_Image/'
#输出目录
OutPath = 'C:/Users/Eric/Desktop/python_text/20161214/outpath/'
def processImage(filesoure, destsoure, name, imgtype):
  '''
  filesoure是存放待转换图片的目录
  destsoure是存在输出转换后图片的目录
  name是文件名
  imgtype是文件类型
  '''
  imgtype = 'jpeg' if imgtype == '.jpg' else 'png'
  #打开图片
  im = Image.open(filesoure + name)
  #缩放比例
  rate =max(im.size[0]/640.0 if im.size[0] > 60 else 0, im.size[1]/1136.0 if im.size[1] > 1136 else 0)
  if rate:
    im.thumbnail((im.size[0]/rate, im.size[1]/rate))
  im.save(destsoure + name, imgtype)
def run():
  #切换到源目录,遍历源目录下所有图片
  os.chdir(MyPath)
  for i in os.listdir(os.getcwd()):
    #检查后缀
    postfix = os.path.splitext(i)[1]
    if postfix == '.jpg' or postfix == '.png':
      processImage(MyPath, OutPath, i, postfix)
if __name__ == '__main__':
  run()


          

更多关于Python相关内容可查看本站专题:《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论