python批量图片处理简单示例

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python实现读取命令行参数的方法

本文实例讲述了python读取命令行参数的方法。分享给大家供大家参考。具体分析如下: 如果想对python脚本传参数,python中对应的argc, argv(c语言的命令行参数)是什么...

python实现机械分词之逆向最大匹配算法代码示例

python实现机械分词之逆向最大匹配算法代码示例

逆向最大匹配方法 有正即有负,正向最大匹配算法大家可以参阅/post/127404.htm 逆向最大匹配分词是中文分词基本算法之一,因为是机械切分,所以它也有分词速度快的优点,且逆向最大...

Python中单例模式总结

一、单例模式     a、单例模式分为四种:文件,类,基于__new__方法实现单例模式,基于metaclass方式实现    ...

Python字符串处理之count()方法的使用

 count()方法返回出现在范围内串子数range [start, end]。可选参数的start和end都解释为片符号。 语法 以下是count()方法的语法: str...

python制作mysql数据迁移脚本

用python写了个数据迁移脚本,主要是利用从库将大的静态表导出表空间,载导入到目标实例中。 #!/usr/bin/env python3 #-*- coding:utf8 -*-...