0

How to save generated file content to ImageField in Django? My current code is:

from django.contrib.contenttypes.models import ContentType

image = create_screenshot(url)
print type(image) # <type 'str'>
screenshot = ScreenshotModel(...)
screenshot.image.save('filename.jpg', ContentFile(image), save=True)

This produces no errors while saving, but gives error while trying to show image (using sorl.thumbnail):

IOError: cannot identify image file <cStringIO.StringI object at 0x7fda5322c140>

File is being saved on disk properly, but it is not image and I cannot display it. I have checked file mime type and it is application/octet-stream.

Function create_screenshot generates image using PhantomJS and returns raw output of phantomjs script - when I use it to generate PDF documents and saving it to FileField everything is ok.

EMiDU
  • 654
  • 1
  • 7
  • 24
  • What does the function create_screenshot look like? It clearly doesn't return the screenshot in jpeg format. You should use pillow or something like that to convert the image to jpeg before saving. – Håken Lid Mar 11 '16 at 11:01
  • If the screenshot is returned in png format, you could also just save it as 'filename.png' – Håken Lid Mar 11 '16 at 11:16
  • Possible duplicate of [Convert PILLOW image into StringIO](http://stackoverflow.com/questions/24920728/convert-pillow-image-into-stringio) – Ali Mar 11 '16 at 11:29
  • please read the following answer in order to understand how cStringIO works: http://stackoverflow.com/a/24920879/480424 – Ali Mar 11 '16 at 11:30

0 Answers0