用 tornado 写过一个
流程大概就是取参数去读本地图片, 再缩放尺寸吐出去
import os
import magic
import StringIO
from PIL import Image
from PIL.ExifTags import TAGS
import tornado.web
class img(tornado.web.RequestHandler, tornado.web.StaticFileHandler):
def get_mime(self, path):
mime = magic.Magic(mime=True)
return mime.from_file(path)
def send_img(self, ret, mime_type):
self.set_header("Content-Type", mime_type)
self.set_header('Content-Length', len(ret))
self.finish(ret)
def resize(self, path, size):
mime_type = self.get_mime(path)
if not mime_type or not os.path.exists(path) or not os.path.isfile(path):
raise tornado.web.HTTPError(404)
img = Image.open(path)
_size = tuple([int(s) for s in size.split('x')])
img.thumbnail(_size, Image.ANTIALIAS)
buffer = StringIO.StringIO()
img.save(buffer, mime_type[6:])
ret = buffer.getvalue()
self.send_img(ret, mime_type)
def get(self, path, includ_body=True):
path = self.parse_url_path(path)
abspath = os.path.abspath(os.path.join(self.root, path))
size = self.get_argument('s', None)
if size:
self.resize(abspath, size)
else:
tornado.web.StaticFileHandler.get(self, path, includ_body)