脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python/Django后端使用PIL Image生成头像缩略图

Python/Django后端使用PIL Image生成头像缩略图

2021-06-22 00:13Lockeyi Python

这篇文章主要为大家详细介绍了Python/Django后端使用PIL Image生成头像缩略图,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了python/django后端使用pil image生成头像缩略图的具体代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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})

示例代码中将制作缩略图的函数从基于类的视图中分离出来了(为了清晰起见),实际编程过程中可以定义为类方法方面调用。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/Lockey23/article/details/80659323

延伸 · 阅读

精彩推荐