Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

python - Save image created via PIL to django model

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...