Django imgareaselect手动剪切头像实现方法
本文实例讲述了Djangoimgareaselect手动剪切头像的方法。分享给大家供大家参考。具体如下:
index.html:
<!DOCTYPEhtml> <html> <head> <metacharset="UTF-8"> <title>上传图片</title> </head> <body> <formaction="."method="post"enctype="multipart/form-data">{%csrf_token%} <tableborder="0"> {{form.as_table}} <tr> <td></td> <td><inputtype="submit"value="上传"/></td> </tr> </table> </form> </body> </html>
show.html:
<!DOCTYPEhtml> <html> <head> <metacharset="UTF-8"> <title>HTML5的标题</title> <style> ul{width:80%;padding:5px;} li{list-style:none;float:left;padding:5px;margin:5px;background-color:#ccc;} .info{color:green;} </style> </head> <body> <p><ahref="{%urlheadhat_index%}">继续上传头像</a></p> {%ifmessages%} {%formessageinmessages%} <p{%ifmessage.tags%}class="{{message.tags}}"{%endif%}>{{message}}</p> {%endfor%} {%endif%} <ul> {%forpinphotos%} <li><imgsrc="{{path}}{{p.photo_name}}"alt="big"/><br/> <imgsrc="{{path}}{{p.photo_thumb}}"alt="thumb"/><ahref="{%urlheadhat_cutp.id%}">继续剪切</a> </li> {%endfor%} </ul> </body> </html>
cut.html:
<!DOCTYPEhtml> <html> <head> <metacharset="UTF-8"> <title>剪切</title> <linkrel="stylesheet"type="text/css"href="/static/jquery.imgareaselect-0.9.3/css/imgareaselect-default.css"/> <stylerel="stylesheet"type="text/css"> .area{ background:nonerepeatscroll00#EEEEFF; border:2pxsolid#DDDDEE; padding:0.6em0.6em1em0.6em; width:85%; display:block; margin-bottom:1em; } div.frame{ background:nonerepeatscroll00#FFFFFF; border:2pxsolid#DDDDDD; padding:0.4em; } .info{color:green;} </style> <scripttype="text/javascript"src="js/jquery.min.js"></script> <scripttype="text/javascript"src="js/jquery.imgareaselect.min.js"></script> <scripttype="text/javascript"> functionpreview(img,selection){ if(!selection.width||!selection.height) return; varscaleX=100/selection.width; varscaleY=100/selection.height; $('#previewimg').css({ width:Math.round(scaleX*300), height:Math.round(scaleY*300), marginLeft:-Math.round(scaleX*selection.x1), marginTop:-Math.round(scaleY*selection.y1) }); $('#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); } $(function(){ $('#id_x1').val(100); $('#id_y1').val(100); $('#id_x2').val(200); $('#id_y2').val(200); $('#id_w').val(100); $('#id_h').val(100); $('#photo').imgAreaSelect({aspectRatio:'1:1',handles:true, fadeSpeed:200,minHeight:100,minWidth:100,onSelectChange:preview, x1:100,y1:100,x2:200,y2:200 }); }); </script> </head> <body> <h3>头像剪切<ahref="{%urlheadhat_index%}"><b>返回</b></a></h3> {%ifmessages%} {%formessageinmessages%} <p{%ifmessage.tags%}class="{{message.tags}}"{%endif%}>{{message}}</p> {%endfor%} {%endif%} <divclass="area"> <divstyle="float:left;width:45%;"> <pclass="instructions">点击原图选择剪切区域</p> <divstyle="margin:0pt0.3em;width:300px;height:300px;"class="frame"> <imgsrc="{{vir_path}}"id="photo"alt="30"/> </div> </div> <divstyle="float:left;width:40%;padding-top:50px;"> <pstyle="font-size:110%;font-weight:bold;padding-left:0.1em;">预览选择区域</p> <divstyle="margin:0pt1em;width:100px;height:100px;"class="frame"> <divstyle="width:100px;height:100px;overflow:hidden;"id="preview"> <imgstyle="width:244px;height:244px;margin-left:-71px;margin-top:-54px;"src="{{vir_path}}"alt="300"/> </div> </div> <formaction=""method="POST">{%csrf_token%} <tablestyle="margin-top:1em;"> <thead> <tr> <thstyle="font-size:110%;font-weight:bold;text-align:left;padding-left:0.1em;"colspan="2"> 剪切坐标 </th> <thstyle="font-size:110%;font-weight:bold;text-align:left;padding-left:0.1em;"colspan="2"> 剪切尺寸 </th> </tr> </thead> <tbody> <tr> <tdstyle="width:10%;"><b>X<sub>1</sub>:</b></td> <tdstyle="width:30%;">{{form.x1}}</td> <tdstyle="width:20%;"><b>宽度:</b></td> <td>{{form.w}}</td> </tr> <tr> <td><b>Y<sub>1</sub>:</b></td> <td>{{form.y1}}</td> <td><b>高度:</b></td> <td>{{form.h}}</td> </tr> <tr> <td><b>X<sub>2</sub>:</b></td> <td>{{form.x2}}</td> <td></td> <td></td> </tr> <tr> <td><b>Y<sub>2</sub>:</b></td> <td>{{form.y2}}</td> <td></td> <td><inputtype="submit"value="保存"/></td> </tr> </tbody> </table> </form> </div> <divstyle="clear:left;"></div> </div> </body> </html>
forms.py:
#coding=utf-8 fromdjangoimportforms classPhotoForm(forms.Form): photo_name=forms.ImageField(label=u"头像") classHatHeadCutForm(forms.Form): x1=forms.IntegerField(widget=forms.TextInput(attrs={'size':4,})) y1=forms.IntegerField(widget=forms.TextInput(attrs={'size':4,})) x2=forms.IntegerField(widget=forms.TextInput(attrs={'size':4,})) y2=forms.IntegerField(widget=forms.TextInput(attrs={'size':4,})) w=forms.IntegerField(widget=forms.TextInput(attrs={'size':4,})) h=forms.IntegerField(widget=forms.TextInput(attrs={'size':4,}))
models.py:
#coding=utf-8 fromdjango.dbimportmodels classPhoto(models.Model): photo_name=models.CharField(u"图片路径",max_length=255) photo_thumb=models.CharField(u"图片缩略图",max_length=255)
views.py:
#coding=utf-8 fromdjango.core.urlresolversimportreverse fromdjango.shortcutsimportrender_to_response,get_object_or_404 fromdjango.httpimportHttpResponse,HttpResponseRedirect fromdjango.templateimportRequestContext fromdjango.contribimportmessages importos,uuid,ImageFile,Image fromPhotoCut.headhat.formsimportPhotoForm,HatHeadCutForm fromPhotoCut.headhat.modelsimportPhoto fromPhotoCut.settingsimportMEDIA_ROOT,HEADHAT_ABS_PATH,HEADHAT_VIR_PATH defindex(request,templates="headhat/index.html"): template_var={} form=PhotoForm() ifrequest.method=="POST": form=PhotoForm(request.POST.copy(),request.FILES) ifform.is_valid(): file=request.FILES.get("photo_name",None) iffile: p=ImageFile.Parser() forcinfile.chunks(): p.feed(c) img=p.close() ifimg.mode!='RGBA': img=img.convert('RGBA') ifimg.size[0]>img.size[1]: offset=int(img.size[0]-img.size[1])/2 img=img.crop((offset,0,int(img.size[0]-offset),img.size[1])) else: offset=int(img.size[1]-img.size[0])/2 img=img.crop((0,offset,img.size[0],(img.size[1]-offset))) img.thumbnail((300,300)) file_name="%s.jpg"%str(uuid.uuid1()) img.save(os.path.join(HEADHAT_ABS_PATH,file_name),"JPEG",quality=100) messages.info(request,u"上传成功!") p=Photo.objects.create(photo_name=file_name) p.save() returnHttpResponseRedirect(reverse("headhat_cut",kwargs={"id":p.id})) template_var["form"]=form returnrender_to_response(templates,template_var,context_instance=RequestContext(request)) defcut(request,id,templates="headhat/cut.html"): template_var={} p=get_object_or_404(Photo,pk=int(id)) ifnotp.photo_name: messages.info(request,u"请先上传图片!") returnHttpResponseRedirect(reverse("headhat_index")) template_var["vir_path"]=os.path.join(HEADHAT_VIR_PATH,p.photo_name) form=HatHeadCutForm() ifrequest.method=='POST': form=HatHeadCutForm(request.POST) ifform.is_valid(): try: img=Image.open(os.path.join(HEADHAT_ABS_PATH,p.photo_name)) exceptIOError: messages.info(request,u"读取文件错误!") data=form.cleaned_data img=img.crop((data["x1"],data["y1"],data["x2"],data["y2"])) img.thumbnail((50,50)) file_name="%s_%s"%(os.path.splitext(p.photo_name)[0],"_50_50.jpg") img.save(os.path.join(HEADHAT_ABS_PATH,file_name),"JPEG",quality=100) p.photo_thumb=file_name p.save() messages.info(request,u"剪切成功!") returnHttpResponseRedirect(reverse("headhat_show")) else: messages.info(request,u"请剪切后再保存!") template_var["form"]=form returnrender_to_response(templates,template_var,context_instance=RequestContext(request)) defshow(request,templates="headhat/show.html"): template_var={} photos=Photo.objects.all() template_var["path"]=HEADHAT_VIR_PATH template_var["photos"]=photos returnrender_to_response(templates,template_var,context_instance=RequestContext(request))
希望本文所述对大家的Python程序设计有所帮助。