Example of django's method for uploading images and generating thumbnails

  • 2020-06-15 09:37:01
  • OfStack

django processing uploaded images to generate thumbnails first note that the form tag must have enctype="multipart/ form-ES6en "attribute, in addition to install the PIL library, then it is very simple, here is the example code:

upload.html


<div id="uploader"> 
  <form id="upload" enctype="multipart/form-data" action="/ajax/upload/" method="post"> 
    <input id="file" name="file" type="file"> 
    <input type="submit" value="Upload"> 
  </form> 
</div> 

view.py


# -*- coding: utf-8 -*- 
from django.http import HttpResponse 
import Image 

def upload(request):   
  reqfile = request.FILES['file'] 
  image = Image.open(reqfile) 
  image.thumbnail((128,128),Image.ANTIALIAS) 
  image.save("/home/lhb/1.jpeg","jpeg") 
  return HttpResponse("success.") 

The solution to poor quality thumbnails is described below.

The quality of the thumbnail method used in python's PIL library to generate the thumbnails is poor. It is necessary to use resize method to generate the thumbnails and determine the quality of the thumbnails, as follows:


image = image.resize((x, y), Image.ANTIALIAS)
quality_val = 90
image.save(filename, 'JPEG', quality=quality_val)

conclusion

That's it for the django example of how to upload images and generate thumbnails. Those who are interested can continue to see this site:

Drawing details of turtle built-in module

Python practical applet USES matplotlib module drawing code to share

Python Science drawing code share

If there is any deficiency, please let me know. Thank you for your support!


Related articles: