7

我需要一个在客户端裁剪图像的应用程序,我的意思是,使用像 Jcrop jquery 插件这样的裁剪工具。

我找到了这个工具:

但是最后两个依赖于 admin 并且前两个似乎与他们自己的 ImageFields 和模型非常耦合,有什么好的解决方案吗?

我们正在开发一个具有许多功能的大型应用程序,并且很难更改编写的逻辑

4

1 回答 1

17

我认为这可能是您最好自己编写的东西,因为这取决于您的数据和模型的布局方式,是否(以及在何处)要保存作物,是否要保留原件等。即使你有一个大应用程序,你可能会花更多时间尝试弯曲其他代码来满足你的需要。

(这段代码非常粗糙——我只是在列出这些步骤)

如果您有一个带有图像字段的模型,您可以添加第二个图像字段来保存裁剪后的图像:

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

和一个带有额外字段的表单,用于保存将在客户端的表单中填充的 jcrop 坐标(该字段将被隐藏)。以何种形式将坐标保存到字段中取决于您,但使用 json 字典(客户端的 json.js 和服务器端的 simplejson)可能是一个想法,例如:

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

表格:

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

处理所有这些的视图:

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

以及使用 PIL 创建裁剪图像的函数:

# Look here: http://djangosnippets.org/snippets/224/
def cropper(original_image_path, crop_coords):
    """ Open original, create and return a new cropped image
    ...
于 2011-10-26T20:36:00.083 回答