uploadify+jcrop實現頭像上傳裁剪功能
阿新 • • 發佈:2019-02-05
因為無法debug,斷斷續續幾天才搞定
首先載入各個js和css,都在官網下載~
uploadify.css
jcrop.css
jquery.js
jquery.uploadify.min.js
jcrop.js
步驟:uploadify上傳圖片,得到圖片路徑在前臺顯示使用者上傳的圖片賦給jcrop的id物件,裁剪後點擊儲存,將原始圖片路徑和各個座標傳給php,通過gd庫實現裁剪圖片的生成並儲存到伺服器!
1、uploadify的html
<form> <div id="queue"></div> <input id="file_upload" name="file_upload" type="file" multiple="true"> </form>
2、js部分,包括uploadify上傳,縮圖呈現。
3、後臺php實現將傳過來的座標和圖片進行處理,並儲存到伺服器上。$('#file_upload').uploadify({ 'swf' : 'support/uploadify/uploadify.swf', 'uploader' : 'uploadify.php', 'buttonText' : '+ 選擇圖片', 'fileTypeDesc' : 'All Files', // The description for file types in the browse dialog 'fileTypeExts' : '*.jpg; *.png; *.gif; *.JPG; *.PNG; *.GIF;', 'formData' : {}, 'multi':false, 'removeCompleted' :true, 'onSelectError' : function() { alert( file.name + ' 返回錯誤'); } , 'onUploadSuccess':function(file, data, response) {//data uploadify.php返回資料;response為true false $("#target").attr("src",data);//將使用者上傳的圖片返回給前端,呈現出,省略其他部分程式碼 $("#cropphoto").show(); } }); }); // Create a scope-wide variable to hold the Thumbnailer instance $(function($){ var thumbnail; // Instantiate Jcrop $('#target').Jcrop({ aspectRatio: 1, setSelect: [ 0, 0, 160, 160 ],//預設左上角開始的160*160大小截圖 onSelect: updateCoords//更新座標和大小, },function(){ var jcrop_api = this; thumbnail = this.initComponent('Thumbnailer', { width: 160, height: 160 }); this.ui.preview = thumbnail; }); function updateCoords(c){ $('#x').val(c.x); $('#y').val(c.y); $('#w').val(c.w); $('#h').val(c.h); };
html部分沒有用form提交的格式,用的ajax,傳入使用者上傳的圖片路徑、x、y、w、h
php程式碼:用了gd庫,呼叫影象處理的幾個函式,最後返回裁剪後圖片的地址$newphoto;
$jpeg_quality = 90; $src =$_GET["imgname"];//圖片的路徑地址 $img= imagecreatefromjpeg($src); $dst = ImageCreateTrueColor( 160, 160 ); //建立大小為160的圖片 imagecopyresampled($dst,$img,0,0,$_GET['x'],$_GET['y'], 160,160,$_GET['w'],$_GET['h']);//裁剪 $ext=pathinfo($src, PATHINFO_EXTENSION); $photoname=pathinfo($src, PATHINFO_FILENAME ); $newphoto='upload/aaa.jpg'; //這是路徑,不是檔名 imagejpeg($dst,$newphoto,$jpeg_quality); imagedestroy($img); imagedestroy($dst); echo $newphoto
注意:1、如果發現圖片生成但是是黑色底,基本上是imagecopyresampled這個函式有問題,確認get到值了沒。因為建立圖片的時候預設底色是黑色的
2、jcrop入了點坑,之前看到的縮圖基本用到了this.getBounds 但是看到新的jcrop的document中沒有提到唉,是我沒找到麼。後來還是用demo的thumbnail來實現
3、對於上傳圖片過大需要調整大小的,這裡沒寫,boxWidth什麼的都沒有用。求高人指點~