前台利用jcrop做头像选择预览,后台通过django利用Uploadify组件上传图最终使用PIL做图像裁切
之前一直使用python的PIL自定义裁切图片,今天有需求需要做一个前端的选择预览页面,索性就把这个功能整理一下,分享给大家。
实现思路:
1、前端页面:
用户选择本地一张图片,然后通过鼠标缩放和移动,确定自己所需要的图片切块,最终把图片切块的 左边距,上边距,长,宽这些个参数传给后台
2、后台:
使用的django,主要实现2部分的功能,第一:图片上传,第二:图片裁切
先看一张图片:
前端页面:
后台最后得到的图片:
对于该demo中,我用到了以下js插件:
jquery-webox:弹出图层(你可以不关心)
jcrop:在线裁切预览图片 http://deepliquid.com/content/Jcrop_Implementation_Theory.html
jquery.uploadify:上传附件
html页面:
a)用户信息页面:userinfo.html
b)弹出页面用于用户选择、上传、预览图片:index.html
django程序:
UploadImage模块下有以下几个文件:
c)urls.py
d)views.py
下面就开始贴代码了
a)的代码:
#coding=utf-8from django.http import HttpResponsefrom django.template import RequestContextfrom django.shortcuts import render_to_responseimport os,ImageFile,uuid,shutilfrom django.conf import settingsfrom django.views.decorators.csrf import csrf_exemptfrom django.utils import simplejsonfrom xue_wan_le.Common.CookieUtil import CookieUtil def index(request): ctx=dict() uuid='' marginTop=0 marginLeft=0 width=0 height=0 if request.GET.get('marginTop'): marginTop=int(request.GET.get('marginTop')) if request.GET.get('marginLeft'): marginLeft=int(request.GET.get('marginLeft')) if request.GET.get('width'): width=int(request.GET.get('width')) if request.GET.get('height'): height=int(request.GET.get('height')) if request.GET.get('uuid'): uuid=request.GET.get('uuid') print '===uuid:'+request.GET.get('uuid') request.session['replace_site_icon_uuid'] = uuid#保存UUID if request.GET.get('replace_flag'): filepath=request.GET.get('savepath') olduuid=request.session['replace_site_icon_uuid'] print '===filepath:'+filepath print '===olduuid:'+olduuid print '====uuid:'+uuid path=os.path.join(settings.MEDIA_ROOT,settings.SOURCE_IMAGE_TMP) if filepath and olduuid: if os.path.isfile(os.path.join(path,filepath)): #先把新文件,换成旧文件名字 try: print 'olduuid:'+olduuid newname=os.path.join(settings.MEDIA_ROOT,settings.SOURCE_IMAGE_TMP,olduuid+'.jpg') print 'newname:'+newname os.rename(os.path.join(path,filepath),newname) #覆盖 shutil.move(os.path.join(settings.MEDIA_ROOT,settings.SOURCE_IMAGE_TMP,olduuid+'.jpg'), os.path.join(settings.MEDIA_ROOT,'urls','sitethumbs',olduuid+'.jpg')) #裁切 try: from PIL import Image path=os.path.join(settings.MEDIA_ROOT,'urls','sitethumbs',olduuid+'.jpg') f = Image.open(path) xsize,ysize=f.size print 'image size:'+str(xsize)+":"+str(ysize) #box变量是一个四元组(左,上,右,下)。 box=(marginLeft,marginTop,marginLeft+width,marginTop+height) print box print '----1' f.crop(box).save(path) print '----2' print 'crop image:'+path except Exception,e: print e return HttpResponse(simplejson.dumps({'message':'替换成功,关闭窗口'})) except Exception,e: print e else: print 'error.==' if request.method=="POST": file = request.FILES.get("Filedata",None) (upload_flag,savepath)=_upload(file) if upload_flag: ctx["message"]=u"上传成功!" ctx["upload_flag"]=1 else: ctx["message"]=u"上传出错!" ctx["upload_flag"]=0 ctx["savepath"]=savepath return render_to_response("uploadpic/index.html",ctx,RequestContext(request))@csrf_exemptdef uploadify_script(request): response=HttpResponse() response['Content-Type']="text/javascript" ret="0" file = request.FILES.get("Filedata",None) if file: if _upload(file): ret="1" ret="2" response.write(ret) return responsedef _upload(file): '''图片上传函数''' if file: path=os.path.join(settings.MEDIA_ROOT,settings.SOURCE_IMAGE_TMP) if not os.path.exists(path): #如果目录不存在创建目录 os.makedirs(path) file_name=str(uuid.uuid1())+".jpg" path_file=os.path.join(path,file_name) parser = ImageFile.Parser() for chunk in file.chunks(): parser.feed(chunk) img = parser.close() try: if img.mode != "RGB": img = img.convert("RGB") img.save(path_file, 'jpeg',quality=100) print 'img.save:'+path_file except Exception,e: print e return (False,"") return (True,file_name) return (False,"")
index.html和view.py是功能实现的主要部分,如果有疑问可以发评论给我,或者新浪微博私信给我http://weibo.com/changeself