Home  >  Article  >  Backend Development  >  Python's Tornado framework implements image uploading and image size modification

Python's Tornado framework implements image uploading and image size modification

高洛峰
高洛峰Original
2017-03-01 13:46:292057browse

Uploading pictures

Upload pictures using form submission. The following is the html part. enctype="multipart/form-data" means that the bytes will not be encoded and uploaded. The file type needs to be specified. The type="file" of the input tag specifies the upload type.

<form action="/" enctype="multipart/form-data" method="post">
  <input type="file" name="headimg">
</form>

The following is the part where tornado accepts files

class UploadHandler(BaseHandler):
  def post(self):
    # 这部分就是上传的文件,想要查看更多可以print self.request看看
    # 该文件返回一个元素为字典的列表
    imgfile = self.request.files.get(&#39;headimg&#39;)
    for img in imgfile:
      # img有三个键值对可以通过img.keys()查看
      # 分别是 &#39;filename&#39;, &#39;body&#39;, &#39;content_type&#39; 很明显对应着文件名,内容(二进制)和文件类型
      with open(&#39;./static/uploads/&#39; + img[&#39;filename&#39;], &#39;wb&#39;) as f:
        # 文件内容保存 到&#39;/static/uploads/{{filename}}&#39;
        f.write(f[&#39;body&#39;])

This way you can access it through the file name of /static/uploads/

Modify the image size

The following will be written to resize the image

class UploadHandler(BaseHandler):
  @tornado.web.authenticated
  def post(self):
    # 应该写到上面, 为了显示写到了函数内
    import time
    # PIL 是 python中对图片进行操作的模块, 感兴趣可以去看一下
    from PIL import Image
    # 可以想文件一样使用, 只是存放在内存
    from cStringIO import StringIO

    # 判断上传文件大小
    size = int(self.request.headers.get(&#39;Content-Length&#39;))
    if size / 1000.0 > 2000:
      self.write("上传图片不能大于2M.")
    imgfile = self.request.files.get(&#39;headimg&#39;)
    for img in imgfile:
      # 对文件进行重命名
      name = str(time.strftime(&#39;%Y%m%d%&#39;), time.localtime())\
          + &#39;_&#39; + self.current_user + &#39;_headimg.png&#39;

      with open(&#39;./static/uploads/&#39; + name, &#39;wb&#39;) as f:
        # image有多种打开方式,一种是 Image.open(&#39;xx.png&#39;)
        # 另一种就是 Image.open(StringIO(buffer)) 
        im = Image.open(StringIO(img[&#39;body&#39;]))
        # 修改图片大小resize接受两个参数, 第一个是宽高的元组数据,第二个是对图片细节的处理,本文表示抗锯齿
        im = im.resize((72, 72), Image.ANTIALIAS)
        # 打开io 就像文件一样
        im_file = StringIO()
        im.save(im_file, format=&#39;png&#39;)
        # 这是获取io中的内容
        im_data = im_file.getvalue() 
        f.write(im_data)

so that the file size can be modified when uploading

More Python's Tornado framework Please pay attention to the PHP Chinese website for related articles on image uploading and image size modification!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn