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 含子图的gif生成时内存溢出的方法

今天想用python做个demo,含两个子图的动态gif,代码如下: import matplotlib.pyplot as plt import imageio,os import...

python的paramiko模块实现远程控制和传输示例

本文介绍了python的paramiko模块实现远程控制和传输示例,分享给大家,具体如下: 1 安装 sudo pip install paramiko 2 ssh实现远程控制...

python遍历目录的方法小结

本文实例总结了python遍历目录的方法。分享给大家供大家参考,具体如下: 方法一使用递归: """ def WalkDir( dir, dir_callback = None, f...

Python中url标签使用知识点总结

Python中url标签使用知识点总结

1.在模板中,我们经常要使用一些url,实现页面之间的跳转,比如某个a标签中需要定义href属性。当然如果通过硬编码的方式直接将这个url固定在里面也是可以的,但是这样的话,对于以后进行...

python numpy元素的区间查找方法

找了半天,以为numpy的where函数像matlab 的find函数一样好用,能够返回一个区间内的元素索引位置。结果没有。。(也可能是我没找到) 故自己写一个函数,找多维数组下的,在某...