为了在上传时调整图像大小(使用 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/