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

yipeiwu_com6年前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设计】。

相关文章

Python 读取串口数据,动态绘图的示例

Python 读取串口数据,动态绘图的示例

最近工作需要把单片机读取的传感器电压数据实时在PC上通过曲线显示出来,刚好在看python, 就试着用了python 与uart端口通讯,并且通过matplotlib.pyplot 模块...

批量将ppt转换为pdf的Python代码 只要27行!

这是一个Python脚本,能够批量地将微软Powerpoint文件(.ppt或者.pptx)转换为pdf格式。 使用说明 1、将这个脚本跟PPT文件放置在同一个文件夹下。 2、运行这个脚...

Python 限定函数参数的类型及默认值方式

python作为一门动态语言,在使用变量之前是不需要进行定义,而是通过动态绑定的方法将变量绑定为某种类型。这样做为我们使用变量时提供了方便,但有时也给我们使用变量时造成了一定的困扰,例如...

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

今天在网上copy的一段代码,代码很简单,每行看起来该缩进的都缩进了,运行的时候出现了如下错误:  【解决过程】  1.对于此错误,最常见的原因是,的确没有缩进。...

pytorch中tensor.expand()和tensor.expand_as()函数详解

tensor.expend()函数 >>> import torch >>> a=torch.tensor([[2],[3],[4]]) >...