一例tornado框架下处理上传图片并生成缩略图的例子

class coachpic(RequestHandler):
    @gen.coroutine
    def post(self):
        picurl = self.request.files['picurl'][0]
        print("picurl:{}".format(picurl))
        ret = yield self.editpic(picurl)
        self.write(ret)
    @gen.coroutine
    def editpic(self,picfile):
        filename = picfile["filename"]
        current_path = os.getcwd()
        print("cwd:{}".format(current_path))
        originpath = current_path + "/templates/static/pics/coach/"
        if os.path.exists(originpath) == False:
            os.mkdir(originpath)
        with open( originpath+ filename, "wb") as picwriter:
            picwriter.write(picfile["body"])
        saiwa = Image.open(originpath+ filename)
        width = saiwa.size[0]
        height = saiwa.size[1]
        portion = 200 / height
        width = round(width * portion, 2)
        height = round(height * portion, 2)
        saiwa.thumbnail((width, height))
        thpath = os.getcwd() + "/templates/static/thumbnail/coach/"
        if os.path.exists(thpath) == False:
            os.mkdir(thpath)
        saiwa.save(thpath + "th_" + filename)
        print("宽{},高{}".format(width, height))
        originsrc = "/static/pics/coach/" + filename
        subsrc = "/static/thumbnail/coach/" + "th_" + filename
        raise Return({"origin": originsrc, "subsrc": subsrc})

 

posted @ 2019-05-30 23:33  saintdingtheGreat  阅读(429)  评论(0编辑  收藏  举报