Django - 获取 PIL 图像保存方法以与 Amazon s3boto 存储一起使用

标签 django amazon-s3 python-imaging-library boto

为了在上传时调整图像大小(使用 PIL),我重写了文章模型的保存方法,如下所示:

def save(self):
    super(Article, self).save()
    if self.image:
        size = (160, 160)
        image = Image.open(self.image)
        image.thumbnail(size, Image.ANTIALIAS) 
        image.save(self.image.path)

这在本地有效,但在生产中我收到错误: NotImplementedError:此后端不支持绝对路径。

我尝试将 image.save 行替换为

image.save(self.image.url)

但随后我收到一个 IOError: [Errno 2] 没有这样的文件或目录:' https://my_bucket_name.s3.amazonaws.com/article/article_images/2.jpg '

不过,这是图像的正确位置。如果我将该地址输入浏览器,图像就在那里。我尝试了许多其他方法,但到目前为止,还没有成功。

最佳答案

您应该尝试避免保存到绝对路径;有一个File Storage API它为您抽象了这些类型的操作。

查看PIL Documentation ,看来 save() 函数支持传递类似文件的对象而不是路径。

我不在可以测试此代码的环境中,但我相信您需要执行类似的操作而不是最后一行:

from django.core.files.storage import default_storage as storage

fh = storage.open(self.image.name, "w")
format = 'png'  # You need to set the correct image format here
image.save(fh, format)
fh.close()

关于Django - 获取 PIL 图像保存方法以与 Amazon s3boto 存储一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14680323/

相关文章:

python - 如何创建一个 'urlpattern' 且数量不定的 'named regex groups'

django - 如何在特定时间(例如午夜)清除 Django 模板缓存?

django - 如何覆盖 Django admin `change_list.html` 以随时随地提供格式

python - 将 S3 数据加载到 AWS SageMaker Notebook

hadoop - 将中间 Amazon EMR 任务输出写入 S3

javascript - 桌面/iOS SAFARI 中的 MP3 文件持续时间无限

python - 如何将分割的图像与重叠合并

python - Gif 帧持续时间似乎比预期慢

django - 如何将多个查询集混合为一个查询集并按创建时间重新排序?

Django - 手动将图像保存到 ImageField 字段