Django app for image crop using a cropping tool

2019-03-08 12:34发布

问题:

I need an app for crop an image in the client side, I mean, using a cropping tool like Jcrop jquery plugin.

I found this tools:

  • django-image-cropper
  • django-image-cropping
  • django-imagehandler
  • django-avatar-crop

But the last two depends of admin and the two first seem very coupled to ther own ImageFields and models, any good solution?

We are working over a big application with many features and is very difficult change the logic writed

回答1:

I think this is something that you will probably be best off writing yourself as it depends on how your data and models are layed out, whether (and where) you want to save the crops, if you want to keep the originals etc. Even if you have a big app, you will probably spend more time trying to bend other code to do what you need in your situation.

(This code is very rough - I'm just laying out the steps really)

If you have a model with an imagefield, you could add a second image field to hold the cropped image:

class MyModel(models.Model):
    image = models.ImageField(...)
    image_crop = models.ImageField(...)

and a form with an extra field to hold the jcrop coordinates that will be populated in the form on the client side (the field will be hidden). In what form you save the coordinates into the field is up to you, but it might be an idea to use a json dictionary (json.js on the client side and simplejson on the server side), something like:

{ 'x1' : '145', 'y1' : '200'  ... }

the form:

class MyModelForm(form.ModelForm):
    """ Hide a field to hold the coordinates chosen by the user """
    crop_coords = forms.CharField(attrs={'style':'display:none'})        

    class Meta:
         model = MyModel

a view that processes all this:

def some_view(request):
    form = request.POST
    if form.is_valid():
        crop_coords = form.cleaned_data['crop_coords']
        # decode the coords using simpleson (or however you passed them)
        ...
        # create a cropped image 
        original_image = form.cleaned_data['image']
        cropped_image = cropper(original_image.path, crop_coords)
        ...
        # save it back to the db - http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-django-imagefield
        ...

and a function to create the cropped image using PIL:

# Look here: http://djangosnippets.org/snippets/224/
def cropper(original_image_path, crop_coords):
    """ Open original, create and return a new cropped image
    ...