将通过PIL创建的图像保存到django模型

时间:2021-10-12 06:20:44

I have successfully created and rotated an image that was uploaded via email to a directory on my server using the following code:

我已使用以下代码成功创建并旋转了通过电子邮件上传到我服务器上的目录的图像:

      image = ContentFile(b64decode(part.get_payload()))
      im = Image.open(image)
      tempfile = im.rotate(90)
      tempfile.save("/srv/www/mysite.com/public_html/media/images/rotate.jpg", "JPEG")
      img = Photo(user=user)
      img.img.save('rotate.jpg', tempfile)
      img.save()

The rotated image exists in the directory, however when I try to add that image to my model, it is not saving. What am I missing? Any help would be greatly appreciated.

旋转的图像存在于目录中,但是当我尝试将该图像添加到我的模型时,它不会保存。我错过了什么?任何帮助将不胜感激。

1 个解决方案

#1


15  

I solved the issue with the following code:

我用以下代码解决了这个问题:

       image = ContentFile(b64decode(part.get_payload()))
       im = Image.open(image)
       tempfile = im.rotate(270)
       tempfile_io =StringIO.StringIO()
       tempfile.save(tempfile_io, format='JPEG')
       image_file = InMemoryUploadedFile(tempfile_io, None, 'rotate.jpg','image/jpeg',tempfile_io.len, None)
       img = Photo(user=user)
       img.img.save('rotate.jpg', image_file)
       img.save()

I found the answer here How do you convert a PIL `Image` to a Django `File`?. Works flawlessly!!!

我在这里找到了答案你如何将PIL`Image`转换为Django`File`?完美无瑕!!!

#1


15  

I solved the issue with the following code:

我用以下代码解决了这个问题:

       image = ContentFile(b64decode(part.get_payload()))
       im = Image.open(image)
       tempfile = im.rotate(270)
       tempfile_io =StringIO.StringIO()
       tempfile.save(tempfile_io, format='JPEG')
       image_file = InMemoryUploadedFile(tempfile_io, None, 'rotate.jpg','image/jpeg',tempfile_io.len, None)
       img = Photo(user=user)
       img.img.save('rotate.jpg', image_file)
       img.save()

I found the answer here How do you convert a PIL `Image` to a Django `File`?. Works flawlessly!!!

我在这里找到了答案你如何将PIL`Image`转换为Django`File`?完美无瑕!!!