PIL对上传到Django的图片进行处理并保存的实例

yipeiwu_com5年前Python基础

1. 介绍

上传的图片文件:如

pic = request.FILES["picture"]
# pic是 <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> 类型的数据

# 而pillow的Image.open("./xxx.jpg") 则是:

<class 'PIL.JpegImagePlugin.JpegImageFile'> 类型的数据

# 问题是如何把InMemoryUploadedFile转化为PIL类型,并且处理之后再转回InMemoryUploadedFile,并save

2. 把InMemoryUploadedFile转化为PIL类型

from PIL import Image

pic = request.FILES["picture"]
im_pic = Image.open(pic)
# 这样就把InMemoryUploadedFile转化为了PIL类型数据,pic是InMemoryUploadedFile,im_pic是PIL类型

3. 处理PIL类型的图片数据

w, h = im_pic.size
if w >= h:
  w_start = (w-h)*0.618
  box = (w_start, 0, w_start+h, h)
  region = im_pic.crop(box)
else:
  h_start = (h-w)*0.618
  box = (0, h_start, w, h_start+w)
  region = im_pic.crop(box)

# region就是PIL处理后的正方形了

4. 将处理后的PIL类型转化为InMemoryUploadedFile类型

from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile

// 先保存到磁盘io
pic_io = BytesIO()
region.save(pic_io, im_pic.format)
// 再转化为InMemoryUploadedFile数据
pic_file = InMemoryUploadedFile(
  file=pic_io,
  field_name=None,
  name=pic.name,
  content_type=pic.content_type,
  size=pic.size,
  charset=None
)

pic_file 就是region转化后的InMemoryUploadedFile了

5. 保存InMemoryUploadedFile到数据库

from ./models import Picture

p = Picture(picture=pic_file)
p.save()

以上这篇PIL对上传到Django的图片进行处理并保存的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django 多表关联 存储 使用方法详解 ManyToManyField save

当models中使用ManyToManyField进行多表关联的时候,需要使用字段的add()方法来增加关联关系的一条记录,让两个实例关联起来才能顺利保存关联关系 #models.p...

tensorflow 获取所有variable或tensor的name示例

获取所有variable(每个op中可训练的张量)的name: for variable_name in tf.global_variables(): print(variabl...

Python中将dataframe转换为字典的实例

有时候,在Python中需要将dataframe类型转换为字典类型,下面的方法帮助我们解决这一问题。 任务代码。 # encoding: utf-8 import pandas a...

python 实现敏感词过滤的方法

如下所示: #!/usr/bin/python2.6 # -*- coding: utf-8 -*- import time class Node(object): d...

python算法表示概念扫盲教程

python算法表示概念扫盲教程

本文为大家讲解了python算法表示概念,供大家参考,具体内容如下 常数阶O(1) 常数又称定数,是指一个数值不变的常量,与之相反的是变量 为什么下面算法的时间复杂度不是O(3),而是O...