Python Show-Me-the-Code 第 0022 题 批量图片处理2
2015-06-18 00:36
696 查看
第 0022 题: iPhone 6、iPhone 6 Plus 早已上市开卖。请查看你写得 第 0005 题的代码是否可以复用。
思路:
跟第五题一样,遍历给出目录下的图片,把大于iPhone5分辨率的图片都进行缩放。使用Python的PIL库对图片进行处理,IPhone5屏幕分辨率为640 × 1136,将大于该分辨率的图片按照一定比例缩放至适合大小并保存。由于第五题已经写过相关函数,就改动一下变成可以根据给出的型号来转换的就行。代码:
0022.批量图片处理2.py#!/usr/bin/env python #coding: utf-8 import Image, os # 源目录 myPath = '/home/bill/Pictures/' # 输出目录 outPath = '/home/bill/Pictures/output/' # 记录不同iPhone型号分辨率 size_config = { 'iPhone5': { 'height': 1136, 'weight': 640 }, 'iPhone6': { 'height': 1334, 'weight': 750 }, 'iPhone6Plus': { 'height': 2208, 'weight': 1242 } } def processImage(filesource, destsource, name, imgtype, phonetype='iPhone5'): ''' filesource是存放待转换图片的目录 destsource是存放输出转换后图片的目录 name是文件名 imgtype是文件类型 phonetype是手机类型 ''' maxsize = size_config[phonetype] imgtype = 'jpeg' if imgtype == '.jpg' else 'png' #打开图片 im = Image.open(filesource + name) # 缩放比例 rate = max(im.size[0]/float(maxsize['weight']) if im.size[0] > maxsize['weight'] else 0, im.size[1]/float(maxsize['height']) if im.size[1] > maxsize['height'] else 0) if rate: im.thumbnail((im.size[0]/rate, im.size[1]/rate)) im.save(destsource + name, imgtype) def run(myPath, outPath, phonetype): # 切换到源目录,遍历源目录下所有图片 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, phonetype) if __name__ == '__main__': run(myPath, outPath, 'iPhone6')
相关文章推荐
- Python中的json操作
- Python里面这些点,据说80%的新手都会一脸懵逼
- Python抽象类的新写法
- Python的time模块中的常用方法整理
- 举例详解Python中threading模块的几个常用方法
- Python自然语言处理(1):初识NLP
- python模块MySQLdb
- 21行Python写出拼写检查器
- python scrapy爬取动态页面
- Python学习笔记之基本语法
- 20150617-Python,Django安装
- 20150617-Python冒泡排序
- python可变参数调用函数的问题
- 使用android模拟事件,python完成自动化测试
- python学习笔记
- Python 装饰器
- Leetcode—Contains Duplicate II—Python
- Leetcode—Contains Duplicate—Python的三种写法
- 用Python提取XML里的内容,存到Excel中
- 机器学习算法与Python实践之(七)逻辑回归(Logistic Regression)