我通过s3boto使用Amazon S3作为我的存储后端。我有一个带有ImageField的Image模型。通过管理员上传图像时,会成功上传到S3。我现在要做的是使用Pillow创建一个缩略图后保存。我已经验证了缩略图是通过调用它上面的show()方法创建的,但由于某种原因它没有被上传到S3。我认为我保存它的方式可能是错误的 - 任何建议都会受到赞赏。
tasks.py
from celery import shared_task
from .models import Image
import os
from django.core.files.storage import default_storage as storage
from PIL import Image as PillowImage
@shared_task
def create_thumbnails(pk):
try:
image = Image.objects.get(pk=pk)
except Image.ObjectDoesNotExist:
pass
thumbnail_size = (450,200)
filename, ext = os.path.splitext(image.image.name)
try:
fh = storage.open(image.image.name, 'r')
im = PillowImage.open(fh)
im.thumbnail(thumbnail_size)
im.show() # TEST - This opens the resized image in Preview on my mac
filename = filename +'_thumbnail' +ext
new_file = storage.open(filename, 'w')
im.save(new_file, "PNG")
new_file.close()
except IOError as error:
print("cannot create thumbnail for ", filename, 'error ', error)
堆栈
django 1.85
python 2.7.10
答案 0 :(得分:6)
这非常有用,我用它来找到一种方法,从django直接将图像写入s3而不直接使用boto。
基本上PIL的save()方法不适用于s3,但default_storage.write()方法可以。关键是使用default_storage.write()方法直接从StringIO内存文件中写入二进制数据,如下所示:
file_to_write.write(memory_file.getvalue())
这是我在django shell(python manage.py shell)中运行的代码来测试它:
>>> from django.core.files.storage import default_storage as storage
>>> from PIL import Image
>>> import StringIO
>>> i = storage.open('ImageToCreate.jpg','w+')
>>> m = storage.open('ImageAlreadyOnS3.jpg','r')
>>> im = Image.open(m)
>>> im = im.resize((640,360),3)
>>> sfile = StringIO.StringIO() #cStringIO works too
>>> im.save(sfile, format="JPEG")
>>> i.write(sfile.getvalue())
>>> i.close()
>>> m.close()
它也可以在我的views.py中使用。
我发现它很有用,因为它适用于远程s3存储和本地开发环境(笔记本电脑上的文件夹)。
答案 1 :(得分:1)
最后在谷歌搜索非常痛苦的几个小时后才开始工作,主要归功于this博客文章。
<强> tasks.py 强>
from celery import shared_task
import os
from django.core.files.storage import default_storage as storage
from django.conf import settings
import mimetypes
import cStringIO
from PIL import Image as PillowImage
import boto
from .models import Image
@shared_task
def create_thumbnails(pk):
try:
image = Image.objects.get(pk=pk)
except Image.ObjectDoesNotExist:
pass
try:
thumbnail_size = (450,200)
filename, ext = os.path.splitext(image.image.name)
filename = filename +'_thumbnail' +ext
existing_file = storage.open(image.image.name, 'r')
im = PillowImage.open(existing_file)
im = im.resize(thumbnail_size, PillowImage.ANTIALIAS)
memory_file = cStringIO.StringIO()
mime = mimetypes.guess_type(filename)[0]
plain_ext = mime.split('/')[1]
im.save(memory_file, plain_ext)
conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket( 'yourbucketname', validate=False)
k = bucket.new_key('media/' +filename)
k.set_metadata('Content-Type', mime)
k.set_contents_from_string(memory_file.getvalue())
k.set_acl("public-read")
memory_file.close()
except Exception as error:
print("cannot create thumbnail for ", filename, 'error ', error)
答案 2 :(得分:1)
我有同样的问题。
default_storage.write() # It didn't work. it was not saving anything to s3
@RunLoop的答案非常复杂,与我想用Django做的不同,所以,我做了这个并且它有效。
import StringIO
from PIL import Image
首先,阅读上传的文件
image = request.FILES['image'].read() #atleast in my case
创建一个像object这样的文件,以便我们可以使用Image来读取它
image_file = StringIO.StringIO(image)
thumbnail_image = Image.open(image_file)
将图像尺寸调整为所需尺寸
resized_thumbnail_image = thumbnail_image.resize((200, 200), Image.ANTIALIAS)
创建另一个文件,如object或inmemory文件,这样我们就可以将Image实例写入它并获取字符串值 - 应将其传递给默认存储
resized_thumbnail_image_file = StringIO.StringIO()
resized_thumbnail_image.save(resized_thumbnail_image_file, 'JPEG',quality=90)
default_storage.save(save_path, ContentFile(resized_thumbnail_image_file.getvalue()))
我的第一个详细答案,希望它有所帮助。
<强>堆栈: python 2.7 Django 1.8
答案 3 :(得分:0)
请注意,对于Python3,您可能要使用BytesIO:
from io import BytesIO
# 'image' is a PIL image object.
imageBuffer = BytesIO()
image.save(imageBuffer, format=imageType)
imageFile = default_storage.open(imageFileName, 'wb')
imageFile.write(imageBuffer.getvalue())
imageFile.flush()
imageFile.close()