import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile
# Create a file-like object to write thumb data (thumb data previously created
# using PIL, and stored in variable 'thumb')
thumb_io = StringIO.StringIO()
thumb.save(thumb_io, format='JPEG')
# Create a new Django file-like object to be used in models as ImageField using
# InMemoryUploadedFile. If you look at the source in Django, a
# SimpleUploadedFile is essentially instantiated similarly to what is shown here
thumb_file = InMemoryUploadedFile(thumb_io, None, 'foo.jpg', 'image/jpeg',
thumb_io.len, None)
# Once you have a Django file-like object, you may assign it to your ImageField
# and save.
...
class YourModel(Model):
img = models.ImageField(upload_to='photos')
thumb = models.ImageField(upload_to='thumbs')
用法:
#in upload code
uploaded = request.FILES['photo']
from django.core.files.base import ContentFile
file_content = ContentFile(uploaded.read())
new_file = YourModel()
#1 - get it into the DB and file system so we know the real path
new_file.img.save(str(new_file.id) + '.jpg', file_content)
new_file.save()
from PIL import Image
import os.path
#2, open it from the location django stuck it
thumb = Image.open(new_file.img.path)
thumb.thumbnail(100, 100)
#make tmp filename based on id of the model
filename = str(new_file.id)
#3. save the thumbnail to a temp dir
temp_image = open(os.path.join('/tmp',filename), 'w')
thumb.save(temp_image, 'JPEG')
#4. read the temp file back into a File
from django.core.files import File
thumb_data = open(os.path.join('/tmp',filename), 'r')
thumb_file = File(thumb_data)
new_file.thumb.save(str(new_file.id) + '.jpg', thumb_file)
这是python 3.5和django 1.10的实际工作示例
在views.py中:
不必写回文件系统,然后通过一个open调用将文件带回内存的方法是使用StringIO和Django InMemoryUploadedFile。这里有一个简单的例子说明你可以如何做到这一点。这假设您已经有一个名为“thumb”的缩略图:
如果你需要更多的说明,请告诉我。我现在已经在我的项目中工作了,使用django存储上传到S3。我花了一天的时间才找到解决办法。
我不得不在几个步骤中完成这项工作,php中的imagejpeg()需要类似的过程。并不是说没有办法把东西保存在内存中,但是这个方法给你一个原始图像和拇指的文件引用(通常是一个好主意,以防你不得不回去改变拇指的大小)。
型号:
用法:
相关问题 更多 >
编程相关推荐