Python/Django后端使用PIL Image生成头像缩略图
本文实例为大家分享了Python/Django后端使用PIL Image生成头像缩略图的具体代码,供大家参考,具体内容如下
import os from django.views.generic import View from myapp.models import User from PIL import Image def make_thumbnail(infile,thumbnail_dir): size = (156, 156) if not os.path.exists(thumbnail_dir):#判断缩略图存储目录是否存在then新建 os.mkdir(thumbnail_dir) outfile = os.path.join( thumbnail_dir, os.path.basename(infile)) try: im = Image.open(infile)#Key Point im.thumbnail(size)#Key Point im.save(outfile, "JPEG")#Key Point return True except IOError, err: print("cannot create thumbnail for", infile,err) return False class Useravatar(View): def __init__(self): self.thumbnail_dir = os.path.join(STATIC_ROOT, 'avatar/thumbnails') self.dest_dir = os.path.join(STATIC_ROOT, 'avatar/origin_imgs') @method_decorator(login_required) def post(self, request): nt_id = request.session.get('nt_id', 'default') user = User.objects.get(pk=nt_id) if User.objects.filter(pk=nt_id).exists() else None avatarImg = request.FILES['avatar'] if not os.path.exists(self.dest_dir):#判断原图存储目录是否存在then新建 os.mkdir(self.dest_dir) dest = os.path.join(self.dest_dir, nt_id+"_avatar.jpg") with open(dest, "wb+") as destination:#先保存原图 for chunk in avatarImg.chunks(): destination.write(chunk) if make_thumb(dest,self.thumbnail_dir):#使用原图创建缩略图 avartaPath = os.path.join(STATIC_URL, 'avatar/thumbnails', nt_id + "_avatar.jpg") else: avartaPath = os.path.join(STATIC_URL, 'avatar/origin_imgs', nt_id + "_avatar.jpg") User.objects.filter(nt_id=nt_id).update(avatar=avartaPath) return render(request, 'profile.html', {'user': user})
示例代码中将制作缩略图的函数从基于类的视图中分离出来了(为了清晰起见),实际编程过程中可以定义为类方法方面调用。
相关推荐
黑夜流星 2020-06-28
jollyhope 2020-05-10
cbao 2020-02-14
稳哥的小灶 2019-12-27
cherayliu 2019-12-22
TinyDolphin 2019-12-11
gongzhiyao0 2011-08-16
ruizhenggang 2011-08-13
易辰Android 2011-08-10
ChibiMarukoChan 2015-11-18
python的学习之路 2019-04-30
0bytes 2019-04-30
liuwendao 2018-07-14
xiongli 2019-03-27
zongyuewang 2019-03-01
Purgatory00 2019-04-12
HuangXiaoChuan 2016-03-14
齐天 2019-03-18
oDongTianShuiYue 2019-03-21