forked from pyhunterpig/PhotoWall
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imgutil.py
56 lines (48 loc) · 1.76 KB
/
imgutil.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/python
# encoding:utf-8
import math
from cStringIO import StringIO
import Image
QUALITY = 100
def to_data(image):
buf = StringIO()
if image.mode != 'RGB':
image = image.convert('RGB')
image.save(buf, image.format or "JPEG", quality=QUALITY)
val = buf.getvalue()
return val
def rcd(x):
return int(math.ceil(x))
def _crop(size, image):
width, height = size
w, h = image.size
if (w, h) == (width, height):
return to_data(image)
def wrap(image, w, h):
background = Image.new('RGBA', (w, h), (255, 255, 255, 0))
background.paste(image, rcd((w - image.size[0]) / 2.0), rcd((h - image.size[1]) / 2.0))
return background
n = None
if w < width and h <= height:
n = image
if w < width and h > height:
#left upper right lower
n = image.crop((0, (h - height) / 2 , w, h - (h - height) / 2))
if w >= width and h <= height:
n = image.crop(((w - height) / 2, 0 , w - (w - height) / 2, h))
# #小图也要有个大背景
# print size, n
# if n: n = wrap(n, *size)
#
#
#缩略图比原图小的, 先缩放效果会更好
if w >= width and h >= height:
if w * 1.0 / width >= h * 1.0 / height:
thum = (int(w * height * 1.0 / h), height)
image.thumbnail(thum, Image.ANTIALIAS)
n = image.crop((rcd((thum[0] - width)*1.0 / 2.0), 0 , thum[0] - rcd((thum[0] - width)*1.0 / 2.0), thum[1]))
else:
thum = (width, int(h * width * 1.0 / w))
image.thumbnail(thum, Image.ANTIALIAS)
n = image.crop((0, rcd((thum[1] - height)*1.0 / 2.0) , thum[0], thum[1] - rcd((thum[1] - height)*1.0 / 2.0)))
return to_data(n)