結合 jQuery imgAreaSelect 外掛與 Django 後端,實現頭像上傳 → 前端選取裁剪區域 → 後端 Pillow 裁剪生成縮圖完整流程。
<form enctype="multipart/form-data">。imgareaselect,顯示原圖供選取,即時預覽 100x100 縮圖,送出座標。$('#photo').imgAreaSelect({
aspectRatio: '1:1', // 正方形
handles: true, // 顯示調整控制點
fadeSpeed: 200,
minHeight: 100, minWidth: 100,
x1: 100, y1: 100, x2: 200, y2: 200, // 初始選區
onSelectChange: preview // 即時更新預覽與隱藏欄位
});
function preview(img, selection) {
if (!selection.width || !selection.height) return;
var scaleX = 100 / selection.width;
var scaleY = 100 / selection.height;
$('#preview img').css({
width: Math.round(scaleX * 300),
height: Math.round(scaleY * 300),
marginLeft: -Math.round(scaleX * selection.x1),
marginTop: -Math.round(scaleY * selection.y1)
});
// 寫入隱藏 input,表單提交帶往後端
$('#id_x1').val(selection.x1);
$('#id_y1').val(selection.y1);
$('#id_x2').val(selection.x2);
$('#id_y2').val(selection.y2);
$('#id_w').val(selection.width);
$('#id_h').val(selection.height);
}
# forms.py
class CropForm(forms.Form):
x1 = forms.IntegerField(widget=forms.HiddenInput())
y1 = forms.IntegerField(widget=forms.HiddenInput())
x2 = forms.IntegerField(widget=forms.HiddenInput())
y2 = forms.IntegerField(widget=forms.HiddenInput())
w = forms.IntegerField(widget=forms.HiddenInput())
h = forms.IntegerField(widget=forms.HiddenInput())
# views.py
def cut_view(request, photo_id):
photo = get_object_or_404(Photo, id=photo_id)
if request.method == 'POST':
form = CropForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
# Pillow 裁剪
from PIL import Image
im = Image.open(photo.photo.path)
box = (cd['x1'], cd['y1'], cd['x2'], cd['y2'])
thumb = im.crop(box).resize((100, 100), Image.LANCZOS)
# 儲存縮圖...
messages.success(request, '頭像更新成功')
return redirect('show')
else:
form = CropForm(initial={'x1':100,'y1':100,'x2':200,'y2':200,'w':100,'h':100})
return render(request, 'cut.html', {'photo': photo, 'form': form})
jquery.imgareaselect-0.9.3,放入 static/js/、static/css/。{% static 'js/jquery.imgareaselect.min.js' %}。