3

I am wondering how to best implement a croppable ImageField in Django.

Basically i'd like to upload images and crop them. For example using imagAreaSelect

The first approach that came to my mind was to create an ImageField and some meta fields on my model to store the crop ratio, width and height of my selection. But i wonder if the there are cleaner ways to solve this and to further encapsulate the cropping behaviour.

So ultimately i'd like to wrap the desired behaviour in a widget. Though the problem i see is that widgets are usually mapped to single database field.

So i wonder if this is doable at all and how to best persist my image data?

arie
  • 18,737
  • 5
  • 70
  • 76

2 Answers2

3

We ended up creating a reusable app for cropping images: django-image-cropping

arie
  • 18,737
  • 5
  • 70
  • 76
  • the app looks awesome! Is possible to prompt the user to resize and crop the image ? – Lara Apr 12 '16 at 05:50
1

There's a couple ways of doing this. One way is to infer the name of the cropped image from the name of the uncropped image. So if you have an ImageField, and there is an image named uploads/images/family.jpg, your CropableImageWidget might assume that the cropped image is stored at uploads/images/cropped/family.jpg.

The other way is to make your own database field type that stores a serialized representation of all the files you create while cropping. Could be Via JSON.

Donald Stufft
  • 1,148
  • 8
  • 11
  • Hey Donald, thanks for your suggestions. What i don't like about option 1 is that i still have to create a separate upload field. And as i'd really like this functionality to be as encapsulated as possible so that ideally i only have to use my CropImageField in my model definition and don't have to setup other stuff. To serialize the data in a single field came to my mind as well, but then again i'd like to keep most of the functionality of the regular ImageField. What i tried and what really looks promising so far is to use a CompositeField (https://bitbucket.org/mp/django-composite-field) – arie Jul 06 '11 at 08:59