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

yipeiwu_com6年前Python基础

本文实例为大家分享了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})

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈python编译pyc工程--导包问题解决

浅谈python编译pyc工程--导包问题解决

利用python 编译工程,生产pyc文件 pyc文件好处:是一种二进制机器码,并且隐藏了源文件代码,但是有和py文件一样的功能(可以理解为效果一样) 所以可以将代码隐藏,便于商业价值,...

Python脚本实现Web漏洞扫描工具

这是去年毕设做的一个Web漏洞扫描小工具,主要针对简单的SQL注入漏洞、SQL盲注和XSS漏洞,代码是看过github外国大神(听说是SMAP的编写者之一)的两个小工具源码,根据里面的思...

Python3多进程 multiprocessing 模块实例详解

本文实例讲述了Python3多进程 multiprocessing 模块。分享给大家供大家参考,具体如下: 多进程 Multiprocessing 模块 multiprocessing...

Django 批量插入数据的实现方法

项目需求:浏览器中访问django后端某一条url(如:127.0.0.1:8080/get_book/),实时朝数据库中生成一千条数据并将生成的数据查询出来,并展示到前端页面 view...

python DataFrame转dict字典过程详解

python DataFrame转dict字典过程详解

这篇文章主要介绍了python DataFrame转dict字典过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 背景:将商品i...