0

Intro

I have been using Django with easy-thumnails for quite a while, and today I stumbled upon one really nasty bug, but because I have always permitted easy-thumbnails to do as it pleases I consider myself a noob at this.

TL;DR

I need to validate if an image can be read by easy-thumbnails or Pillow before it is saved to the django model in an optimal way.

Explanation

When I tried to convert an .svg image, apparently Pillow crashes on the spot. I don't know if it is because of the format, even though according to some other stack issues, by installing libz or zlib1g, there should not be a problem (they are already installed in my system btw).

Crash Error

But the format doesn't matter, if I insert a corrupt file as an image it could make the library crash every time.

I need to be able to validate (inside my django-forms or my drf-serializers) if an image can be read by pillow before saving it and prevent this to ever happen again.

Any ideas to validate the file in an optimal way would be greatly appreciated.

Community
  • 1
  • 1
Daniel Ortiz
  • 186
  • 9
  • The go-to way of preventing something from saving is by throwing an exception, in this case, you'd want to catch the OSError exception and return an error in your view. – fixmycode Apr 06 '17 at 04:25
  • That could be the case, but the problem is that I have the image loaded in RAM at this point, not a file, and because I'm quite new by using Pillow... I have no idea how to do it without the file path. @fixmycode – Daniel Ortiz Apr 06 '17 at 04:28
  • `def clean_image_field()` worked? – subha.py Apr 06 '17 at 04:36
  • Technically it is not a django-ImageField, easy-thumnails wraps the FileField, so it accepts almost everything. I am trying to solve this one using a custom validation in combination with [this other answer](http://stackoverflow.com/questions/32908639/open-pil-image-from-byte-file). I'll let you know if I am able to fix it @subha.py – Daniel Ortiz Apr 06 '17 at 04:49
  • Can you turn the image into a file-like object using io.StringIO (or StringIO)? https://docs.python.org/3.6/library/io.html?highlight=stringio#io.StringIO – Alex L Apr 06 '17 at 06:06

0 Answers0