Last active
August 29, 2015 14:02
-
-
Save naoyeye/8aa0ff34035142c57e60 to your computer and use it in GitHub Desktop.
python 生成 缩略图
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import Image | |
#生成node 75x75 缩略图 | |
def make_node_thumb(path): | |
base, ext = os.path.splitext(path) | |
try: | |
im = Image.open(path) | |
except IOError: | |
print ' in IOError' | |
return | |
mode = im.mode | |
if mode not in ('L', 'RGB'): | |
if mode == 'RGBA': | |
# 透明图片需要加白色底 | |
im.load() | |
alpha = im.split()[3] | |
bgmask = alpha.point(lambda x: 255-x) | |
im = im.convert('RGB') | |
# paste(color, box, mask) | |
im.paste((255,255,255), None, bgmask) | |
else: | |
im = im.convert('RGB') | |
width, height = im.size | |
# 裁剪图片成正方形 | |
if width > height: | |
delta = (width - height) / 2 | |
box = (delta, 0, width - delta, height) | |
region = im.crop(box) | |
elif height > width: | |
delta = (height - width) / 2 | |
box = (0, delta, width, height - delta) | |
region = im.crop(box) | |
else: | |
region = im | |
filename = base + "_75.jpg" | |
thumb = region.resize((75, 75), Image.ANTIALIAS) | |
# thumb = im.thumbnail((75,75), Image.ANTIALIAS) | |
thumb.save(filename, quality=100) # 默认 JPEG 保存质量是 75, 不太清楚。可选值(0~100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment