forked from Show-Me-the-Code/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0005.py
More file actions
33 lines (29 loc) · 1.06 KB
/
0005.py
File metadata and controls
33 lines (29 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
import os
from PIL import Image
def get_path(root = os.curdir):
root += os.sep
for path, dirs, files in os.walk(root):
for file_name in files:
yield path, file_name
def get_size(width, heigh, max_width, max_heigh):
if width > max_width:
heigh = heigh * (max_width / width)
width = max_width
if heigh > max_heigh:
width = width * (max_heigh / heigh)
heigh = max_heigh
return width, heigh
if __name__ == '__main__':
paths = get_path()
image_format = ('.jpg', '.jpeg', 'png', 'bmp')
max_size = (640, 1136)
for path, file_name in paths:
if file_name.endswith(image_format):
img = Image.open(path + os.sep + file_name)
size = get_size(*(img.size + max_size))
if size != img.size:
img.thumbnail(size)
img.save(path + os.sep + 'thumbnailed_' + file_name)