Python Show-Me-the-Code 第 0005 题 批量图片处理
2015-04-20 18:44
691 查看
第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
思路:遍历给出目录下的图片,把大于iPhone5分辨率的图片都进行缩放。使用Python的PIL库对图片进行处理,IPhone5屏幕分辨率为640 × 1136,将大于该分辨率的图片按照一定比例缩放至适合大小并保存。
0005.批量图片处理.py
思路:遍历给出目录下的图片,把大于iPhone5分辨率的图片都进行缩放。使用Python的PIL库对图片进行处理,IPhone5屏幕分辨率为640 × 1136,将大于该分辨率的图片按照一定比例缩放至适合大小并保存。
0005.批量图片处理.py
#!/usr/bin/env python #coding: utf-8 import Image, os # 源目录 myPath = '/home/bill/Pictures/' # 输出目录 outPath = '/home/bill/Pictures/output/' def processImage(filesource, destsource, name, imgtype): ''' filesource是存放待转换图片的目录 destsource是存放输出转换后图片的目录 name是文件名 imgtype是文件类型 ''' imgtype = 'jpeg' if imgtype == '.jpg' else 'png' #打开图片 im = Image.open(filesource + name) # 缩放比例 rate = max(im.size[0]/640.0 if im.size[0] > 640 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(destsource + 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 Show-Me-the-Code 第 0022 题 批量图片处理2
- Python Show-Me-the-Code 第 0000 题 图片右上角加数字
- Show me the code之Python练习册 Q13 获取网络图片
- Python Show-Me-the-Code 第 0010 题 生成验证码图片
- Python Show-Me-the-Code 第 0013 题 抓取妹子图片 使用scrapy
- Show me the code之Python练习册 Q4~7
- Python Show-Me-the-Code 第 0017,0018,0019 题 写XML文件
- python之os -- show me the code 0005
- 以Python的项目show-me-the-code为例,说明本地git与github
- Show me the code之Python练习册 Q8~9 html解析
- Python Show-Me-the-Code 第 0007 题 统计代码行数(注释,空行,总行数)小程序
- Show me the code之Python练习册 Q14~16 excel操作
- Show me the code之Python练习册 Q10 生成验证码
- Python Show-Me-the-Code 第 0009 题 提取网页中的超链接
- Show me the code之Python练习册 Q11~12 关键词过滤
- Python Show-Me-the-Code 第 0014,0015,0016 题 写Excel文件
- python 之 Counter ---show me the code 0004
- python操作mysql关系数据库 show me the code 0001-0002
- github/python/ show me the code 25题(一)
- Python Show-Me-the-Code 第 0004 题 统计单词