The Tornado framework of Python allows you to upload images and modify the image size,
Image Upload
The uploaded image uses form submission. The following is the html part. enctype = "multipart/form-data" indicates that bytes are not encoded. You must specify the file type when uploading files. 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>
Below is the part of the tornado acceptance File
Class UploadHandler (BaseHandler): def post (self): # This part is the uploaded file. To view more, you can print self. request to see # This file returns a dictionary list of elements imgfile = self. request. files. get ('uploadmg ') for img in imgfile: # img has three key-value pairs available through img. keys () view # 'filename', 'body', and 'content _ type' obviously correspond to the file name, content (Binary), and file type with open ('. /static/uploads/'+ img ['filename'], 'wb') as f: # Save the file content to'/static/uploads/{filename} 'f. write (f ['body'])
In this way, access through/static/uploads/file name
Modify the image size
The following describes how to resize an image.
Class UploadHandler (BaseHandler): @ tornado. web. authenticated def post (self): # It should be written above. In order to display the import time written to the function # PIL is the python module for image operations, if you are interested, please take a look at from PIL import Image # You can use it like a file, but it is stored in the memory from cStringIO import StringIO # determine the size of the uploaded file size = int (self. request. headers. get ('content-length') if size/1000.0> 2000: self. write ("the size of the uploaded image cannot exceed 2 MB. ") imgfile = self. request. files. get ('uploadmg ') for img in imgfile: # rename the file name = str (time. strftime ('% Y % m % d %'), time. localtime () \ + '_' + self. current_user + '_headimg.png 'with open ('. /static/uploads/'+ name, 'wb') as f: # image can be opened in multiple ways. One is Image.open('xx.png ') # The other is Image. open (StringIO (buffer) im = Image. open (StringIO (img ['body']) # modify the image size resize to accept two parameters. The first is the wide and high tuples, and the second is the processing of image details, this article indicates anti-sawtooth im = im. resize (72, 72), Image. ANTIALIAS) # Open io like a file im_file = StringIO () im. save (im_file, format = 'png ') # obtain the content im_data = im_file.getvalue () f in io. write (im_data)
In this way, you can modify the file size during the upload.