python第五题 批量修改图片像素以及学习os模块

ANTIALIAS滤镜缩放结果

参考  : http://www.cnblogs.com/RChen/archive/2007/03/31/pil_thumb.html  

              http://blog.csdn.net/u010417185/article/details/74357382

题目:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。

总体思路:找到目录 开始遍历所有的文件 符合的就再检查文件大小 如果大 ,就改 ,小的就不用管。

import os
from PIL import Image

IPHONE5_WIDTH = 1136
IPHONE5_HEIGHT = 640

# 改变图片的尺寸大小
def reset_pic_size(file_path, new_path, width=IPHONE5_WIDTH, height=IPHONE5_HEIGHT):
image = Image.open(file_path)
image_width, image_height = image.size #这句话挺有意思的 以前见过这种写法 就是image.size有两个参数

if image_width > width:
image_height = width * image_height // image_width #单斜杠:用于传统除法,双斜杠:用于浮点数除法,其结果进行四舍五入。
image_width = width
if image_height > height:
image_width = height * image_width // image_height
image_height = height

new_image = image.resize((image_width, image_height), Image.ANTIALIAS) #滤镜缩放
new_image.save(new_path)


# 从文件夹中循环改变每一张图片
def find_and_resize_pic_from_dir(dir_path):
for root, dirs, files in os.walk(dir_path):
# print(root)
# print(dirs)
# print(files)
#os.walk() 返回值:函数返回一个元组,含有三个元素。这三个元素分别是:每次遍历的路径名、路径下子目录列表、目录下文件列表
for file_name in files:
if file_name.lower().endswith('jpg') or file_name.lower().endswith('png'):
file_path = os.path.join(root, file_name)
file_new_path = 'iPhone5_' + file_name
reset_pic_size(file_path=file_path, new_path=file_new_path)


find_and_resize_pic_from_dir('./')

 涉及到的知识点,就是1.这里依旧用到了第一题中的PIL   2.关于操作文件的目录读取 存放等有关的代码 这部分 应该看import os 这部分模块

os模块学习: 

import os

print(os.getcwd()) #得到当前路径
print(os.listdir(os.getcwd())) #返回列表 列举当前目录下所有文件

print(os.path.abspath('.')) #绝对路径 一个点表示当前目录,两个点表示上级目录。
print(os.path.abspath('..'))

print(os.path.split(os.getcwd())) #将路径分解为(文件夹,文件名),返回的是元组类型

#print(os.path.join(path,path,...)) #将path进行组合,若其中有绝对路径,则之前的path将被删除。

print(os.path.dirname('G:\python文件\poem.txt')) #返回path中的文件夹部分,结果不包含'\'

print(os.path.basename('G:\python文件\poem.txt')) #返回path中的文件名

print(os.path.getmtime('G:\python文件\poem.txt')) #最后修改时间
print(os.path.getatime('G:\python文件\poem.txt')) #最后访问时间
print(os.path.getctime('G:\python文件\poem.txt')) #创建时间

print(os.path.getsize('G:\python文件\poem.txt')) #文件大小

print(os.path.exists('G:\python文件\poem.txt'))
更多请参考:http://blog.chinaunix.net/uid-22414998-id-3424522.html
posted @ 2018-01-31 14:39  BUSYGIRL  阅读(557)  评论(0编辑  收藏  举报