django 处理上传图片生成缩略图首先要注意form标签上必须有enctype="multipart/form-data"属性,另外要装好PIL库, 然后就很简单了,如下是实例代码:
upload.html
1
2
3
4
5
6
|
< 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
1
2
3
4
5
6
7
8
9
10
|
# -*- 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." )
|
下面介绍下生成缩略图质量差的解决办法。
使用python的PIL库的thumbnail方法生成缩略图的质量很差,需要使用resize方法来生成缩略图,并制定缩略图的质量,如下代码:
1
2
3
|
image = image.resize((x, y), Image.ANTIALIAS)
quality_val = 90
image.save(filename, 'JPEG' , quality = quality_val)
|
总结
以上就是本文关于django上传图片并生成缩略图方法示例的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
原文链接:http://outofmemory.cn/code-snippet/35750/django-upload-image-file-make-thumbnail