7

为了在上传时调整图像大小(使用 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] No such file or directory: ' https://my_bucket_name.s3.amazonaws.com/article/article_images/2.jpg '

这是图像的正确位置。如果我将该地址放在浏览器中,图像就在那里。我尝试了许多其他的东西,但到目前为止,没有运气。

4

3 回答 3

13

您应该尽量避免保存到绝对路径;有一个文件存储 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()
于 2013-02-04T05:53:51.920 回答
0

对我来说 default.storage.write() 不起作用, image.save() 不起作用,这个起作用了。如果有人仍然感兴趣,请参阅此代码。我为缩进道歉。我的项目正在使用 Cloudinary 和 Django 小项目。

    from io import BytesIO
    from django.core.files.base import ContentFile
    from django.core.files.storage import default_storage as storage    

    def save(self, *args, **kargs):
    super(User, self).save(*args, **kargs)
    # After save, read the file
    image_read = storage.open(self.profile_image.name, "r")
    image = Image.open(image_read)
        if image.height > 200 or image.width > 200:
           size = 200, 200
        
          # Create a buffer to hold the bytes
           imageBuffer = BytesIO()

          # Resize  
           image.thumbnail(size, Image.ANTIALIAS)

          # Save the image as jpeg to the buffer
           image.save(imageBuffer, image.format)

          # Check whether it is resized
           image.show()

          # Save the modified image
           user = User.objects.get(pk=self.pk)
           user.profile_image.save(self.profile_image.name, ContentFile(imageBuffer.getvalue()))

           image_read = storage.open(user.profile_image.name, "r")
           image = Image.open(image_read)
           image.show()

        image_read.close()
于 2021-06-17T08:26:01.040 回答
0

如果您正在使用Django 中的文件的云存储

NotImplementedError: This backend doesn't support absolute paths

要修复它,您需要替换file.pathfile.name

对于问题中的代码:image.save(self.image.path)withimage.save(self.image.name)

这是控制台中的样子

>>> c = ContactImport.objects.last()

>>> c.json_file.name
'protected/json_files/data_SbLN1MpVGetUiN_uodPnd9yE2prgeTVTYKZ.json'

>>> c.json_file
<FieldFile: protected/json_files/data_SbLN1MpVGetUiN_uodPnd9yE2prgeTVTYKZ.json>

>>> c.json_file.url
'https://storage.googleapis.com/super-secret/media/api/protected/json_files/data_SbLN1MpVGetUiN_uodPnd9yE2prgeTVTYKZ.json?Expires=1631378947&GoogleAccessId=secret&Signature=ga7...'

于 2021-09-10T16:56:18.020 回答