我认为这可能是您最好自己编写的内容,因为这取决于您的数据和模型的布局方式、您是否(以及在何处)要保存作物、是否要保留原件等. 即使你有一个大的应用程序,你也可能会花更多的时间来尝试弯曲其他代码来满足你的需要。
(这段代码很粗糙——我只是在列出步骤)
如果您有一个带有图像域的模型,您可以添加第二个图像域来保存裁剪后的图像:
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
...