PIL對上傳到Django的圖片進行處理並保存
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()