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

yipeiwu_com5年前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实现的各种排序算法代码

复制代码 代码如下:# -*- coding: utf-8 -*-# 测试各种排序算法# link:www.jb51.net# date:2013/2/2 #选择排序def select...

基于python+selenium的二次封装的实现

基于python+selenium的二次封装的实现

这是个人对selenium.webdriver写的一些常用操作的二次封装,也就相当于重写了,不再使用自带的框架,用自己写的框架完成。这样的话使代码更简洁,用自己的思想完成代码的编写。...

Python脚本实现自动发带图的微博

Python脚本实现自动发带图的微博

 要自动发微博最简单的办法无非是调用新浪微博的API(因为只是简单的发微博,就没必要用它的SDK了)。参考开发文档http://open.weibo.com/wiki/API...

python 队列详解及实例代码

python 队列详解及实例代码

队列特性:先进先出(FIFO)——先进队列的元素先出队列。来源于我们生活中的队列(先排队的先办完事)。 Queue模块最常与threading模块一起构成生产-消费者模型,提供了一个适...

对python mayavi三维绘图的实现详解

对python mayavi三维绘图的实现详解

网上下载mayavi的官方帮助文档,里面有很多例子,下面的记录都是查看手册后得到的。 http://code.enthought.com/projects/mayavi/docs/dev...