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文件操作中进行字符串替换的方法(保存到新文件/当前文件)

题目: 1.首先将文件:/etc/selinux/config 进行备份 文件名为 /etc/selinux/config.bak 2.再文件:/etc/selinux/config 中...

Python实现投影法分割图像示例(一)

Python实现投影法分割图像示例(一)

投影法多用于图像的阈值分割。闲话不多说,现用Python实现。 上代码。 import cv2 import numpy img = cv2.imread('D:/0.jpg', c...

余弦相似性计算及python代码实现过程解析

余弦相似性计算及python代码实现过程解析

A:西米喜欢健身 B:超超不爱健身,喜欢打游戏 step1:分词 A:西米/喜欢/健身 B:超超/不/喜欢/健身,喜欢/打/游戏 step2:列出两个句子的并集 西米/喜欢/健身/超...

python 实现数字字符串左侧补零的方法

因为做新闻爬虫,url里面0-9的日期要左侧加零。经过查询之后得到了两种方法。 一、先设一个足够大的数,比如1000000,然后加上当前的数字比如9,得到1000009,然后转化为字符串...

django 消息框架 message使用详解

前言 在网页应用中,我们经常需要在处理完表单或其它类型的用户输入后,显示一个通知信息给用户。 对于这个需求,Django提供了基于Cookie或者会话的消息框架messages,无论是匿...