python批量图片处理简单示例

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Win7上搭建Cocos2d-x 3.1.1开发环境

Win7上搭建Cocos2d-x 3.1.1开发环境

开发工具的准备 搭建开发环境需要安装工具包括 Visual Studio python ———(本教程以python2.7.3版本为例),下载地址:http://www.python.o...

python实现将汉字保存成文本的方法

如果汉字不多的话,建议采取下列方式 首先,在python文件中添加 #coding=utf-8 或者 # -*- coding:utf-8 -*- 然后用一个for循环开始处...

python之PyMongo使用总结

 PyMongo是什么 PyMongo是驱动程序,使python程序能够使用Mongodb数据库,使用python编写而成. 安装 环境:Ubuntu 14.04+pyt...

Python之os操作方法(详解)

1. os.path.driname(path):返回路径的上一级路径字符串。   >>> os.path.dirname('D:\Games')   'D:\\'...

python线程信号量semaphore使用解析

这篇文章主要介绍了python线程信号量semaphore使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.semaphor...