Skip to content

Commit 98dd82c

Browse files
committed
auto downsample large image
1 parent 82ac031 commit 98dd82c

1 file changed

Lines changed: 53 additions & 7 deletions

File tree

facepp.py

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# -*- coding: utf-8 -*-
22
# $File: facepp.py
3-
# $Date: Fri Apr 05 17:29:44 2013 +0800
3+
# $Date: Thu May 16 14:59:36 2013 +0800
44
# $Author: jiakai@megvii.com
55
#
66
# This program is free software. It comes without any warranty, to
@@ -39,25 +39,71 @@
3939
import urllib2
4040
import json
4141
import os
42+
import os.path
4243
import itertools
4344
import mimetools
4445
import mimetypes
4546
import time
47+
import tempfile
4648
from collections import Iterable
4749
from cStringIO import StringIO
4850

4951
class File(object):
5052
"""an object representing a local file"""
5153
path = None
54+
content = None
5255
def __init__(self, path):
5356
self.path = path
54-
55-
def get_content(self):
56-
with open(self.path, 'rb') as f:
57-
return f.read()
57+
self._get_content()
58+
59+
def _resize_cv2(self, ftmp):
60+
try:
61+
import cv2
62+
except ImportError:
63+
return False
64+
img = cv2.imread(self.path)
65+
assert img is not None and img.size != 0, 'Invalid image'
66+
bigdim = max(img.shape[0], img.shape[1])
67+
downscale = max(1., bigdim / 600.)
68+
img = cv2.resize(img,
69+
(int(img.shape[1] / downscale),
70+
int(img.shape[0] / downscale)))
71+
cv2.imwrite(ftmp, img)
72+
return True
73+
74+
def _resize_PIL(self, ftmp):
75+
try:
76+
import PIL.Image
77+
except ImportError:
78+
return False
79+
80+
img = PIL.Image.open(self.path)
81+
bigdim = max(img.size[0], img.size[1])
82+
downscale = max(1., bigdim / 600.)
83+
img = img.resize(
84+
(int(img.size[0] / downscale), int(img.size[1] / downscale)))
85+
img.save(ftmp)
86+
return True
87+
88+
def _get_content(self):
89+
"""read image content; resize the image if necessary"""
90+
91+
if os.path.getsize(self.path) > 2 * 1024 * 1024:
92+
ftmp = tempfile.NamedTemporaryFile(
93+
suffix = '.jpg', delete = False).name
94+
try:
95+
if not (self._resize_cv2(ftmp) or self._resize_PIL(ftmp)):
96+
raise APIError(-1, None, 'image file size too large')
97+
with open(ftmp, 'rb') as f:
98+
self.content = f.read()
99+
finally:
100+
os.unlink(ftmp)
101+
else:
102+
with open(self.path, 'rb') as f:
103+
self.content = f.read()
58104

59105
def get_filename(self):
60-
return self.path
106+
return os.path.basename(self.path)
61107

62108

63109
class APIError(Exception):
@@ -162,7 +208,7 @@ def __call__(self, post = False, *args, **kargs):
162208
for (k, v) in kargs.iteritems():
163209
if isinstance(v, File):
164210
add_form = True
165-
form.add_file(k, v.get_filename(), v.get_content())
211+
form.add_file(k, v.get_filename(), v.content)
166212

167213
if post:
168214
url = self._urlbase

0 commit comments

Comments
 (0)