Chinaunix首页 | 论坛 | 博客
  • 博客访问: 534766
  • 博文数量: 142
  • 博客积分: 2966
  • 博客等级: 少校
  • 技术积分: 1477
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-07 22:37
文章分类

全部博文(142)

文章存档

2013年(3)

2012年(21)

2011年(53)

2010年(33)

2009年(32)

分类: Python/Ruby

2011-05-21 11:22:24

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import Image
  4. import os

  5. def make_thumb(path, sizes=[(98,80),(150,120)]):
  6.     """
  7.     sizes 参数传递要生成的尺寸,可以生成多种尺寸
  8.     """
  9.     base, ext = os.path.splitext(path)
  10.     try:
  11.         im = Image.open(path)
  12.     except IOError:
  13.         return
  14.     mode = im.mode
  15.     if mode not in ('L', 'RGB'):
  16.         if mode == 'RGBA':
  17.             # 透明图片需要加白色底
  18.             alpha = im.split()[3]
  19.             bgmask = alpha.point(lambda x: 255-x)
  20.             im = im.convert('RGB')
  21.             # paste(color, box, mask)
  22.             im.paste((255,255,255), None, bgmask)
  23.         else:
  24.             im = im.convert('RGB')
  25.             
  26.     width, height = im.size
  27.     if width == height:
  28.         region = im
  29.     else:
  30.         if width > height:
  31.             delta = (width - height)/2
  32.             box = (delta, 0, delta+height, height)
  33.         else:
  34.             delta = (height - width)/2
  35.             box = (0, delta, width, delta+width)
  36.         region = im.crop(box)
  37.             
  38.     for size in sizes:
  39.         filename = base + "_" + "%sx%s" % (str(size[0]), str(size[1])) + ".jpg"
  40.         thumb = region.resize((size[0],size[1]), Image.ANTIALIAS)
  41.         thumb.save(filename, quality=100) # 默认 JPEG 保存质量是 75, 不太清楚。可选值(0~100)

  42. if __name__ == '__main__':
  43.     make_thumb(r"c:/kc.jpg")
阅读(2093) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~