php+jquery+Jcrop實現上傳-截取-儲存圖片功能
現在很我網站都流行會員模組上傳頭像時添加線上截取圖片功能,截取完之後再儲存,最近也有很多網友問有沒有這個功能啊,網站上有一款只實現前端截取圖片功能的,至於儲存的話就沒實現,具體可以查看實現圖片截取+預覽功能的jquery外掛程式(http://www.jq-school.com/Detail.aspx?id=45),現在分享用php+jquery+Jcrop實現上傳-截取-儲存圖片功能的,文章後面可以打包下載,學習PHP的網友們可以參考哦。
前端代碼如下:
$(document).ready(function(){var bar = $('.bar');var percent = $('.percent');var showimg = $('#showimg');var progress = $(".progress");var files = $(".files");var btn = $(".btn span");$("#fileupload").wrap("");$("#fileupload").change(function(){ //選擇檔案$("#myupload").ajaxSubmit({dataType: 'json',//資料格式為json beforeSend: function() {//開始上傳 showimg.empty();//清空顯示的圖片progress.show();//顯示進度條var percentVal = '0%';//開始進度為0%bar.width(percentVal);//進度條的寬度percent.html(percentVal);//顯示進度為0% btn.html("上傳中...");//上傳按鈕顯示上傳中},uploadProgress: function(event, position, total, percentComplete) {var percentVal = percentComplete + '%';//獲得進度bar.width(percentVal);//上傳進度條寬度變寬percent.html(percentVal);//顯示上傳進度百分比},success: function(data) {//成功//獲得後台返回的json資料,顯示檔案名稱,大小,以及刪除按鈕files.html(""+data.name+"("+data.size+"k) 刪除");//顯示上傳後的圖片var img = "upload/face/"+data.pic;//判斷上傳圖片的大小 然後設定圖片的高與寬的固定寬if (data.width>240 && data.height<240){showimg.html("");}else if(data.width<240 && data.height>240){showimg.html("");}else if(data.width<240 && data.height<240){showimg.html("");}else{showimg.html("");}//傳給php頁面,進行儲存的圖片值$("#src").val(img);//截取圖片的js$('#cropbox').Jcrop({aspectRatio: 1,onSelect: updateCoords,minSize:[240,240],maxSize:[240,240],allowSelect:false, //允許選擇allowResize:false, //是否允許調整大小setSelect: [ 0, 0, 240, 240 ]});btn.html("上傳圖片");//上傳按鈕還原},error:function(xhr){//上傳失敗btn.html("上傳失敗");bar.width('0')files.html(xhr.responseText);//返回失敗資訊}});});$(".delimg").live('click',function(){var pic = $(this).attr("rel");$.post("action.php?act=delimg",{imagename:pic},function(msg){if(msg==1){files.html("刪除成功.");showimg.empty();//清空圖片progress.hide();//隱藏進度條 }else{alert(msg);}});});});function updateCoords(c){$('#x').val(c.x);$('#y').val(c.y);$('#w').val(c.w);$('#h').val(c.h);};function checkCoords(){if (parseInt($('#w').val())) return true;alert('Please select a crop region then press submit.');return false;};
php後台代碼如下:
1024000) {echo '圖片大小不能超過1M';exit;}$type = strstr($picname, '.');if ($type != ".gif" && $type != ".jpg") {echo '圖片格式不對!';exit;}$rand = rand(100, 999);$pics = date("YmdHis") . $rand . $type;//上傳路徑$pic_path = "upload/face/". $pics;move_uploaded_file($_FILES['mypic']['tmp_name'], $pic_path);}$size = round($picsize/1024,2);$image_size = getimagesize($pic_path);$arr = array('name'=>$picname,'pic'=>$pics,'size'=>$size,'width'=>$image_size[0],'height'=>$image_size[1]);echo json_encode($arr);}?>
打包下載