croppic.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  1. /*
  2. * CROPPIC
  3. * dependancy: jQuery
  4. * author: Ognjen "Zmaj Džedaj" Božičković and Mat Steinlin
  5. */
  6. (function (window, document) {
  7. Croppic = function (id, options) {
  8. var that = this;
  9. that.id = id;
  10. that.obj = $('#' + id);
  11. that.outputDiv = that.obj;
  12. that.imgUrl="";
  13. that.saveImgUrl="";
  14. that.imgBackground="";
  15. // DEFAULT OPTIONS
  16. that.options = {
  17. uploadUrl:'',
  18. uploadData:{},
  19. cropUrl:'',
  20. cropData:{},
  21. outputUrlId:'',
  22. absorptionUrl:'',
  23. //styles
  24. imgEyecandy:true,
  25. imgEyecandyOpacity:0.2,
  26. initialZoom:40,
  27. zoomFactor:10,
  28. rotateFactor:5,
  29. doubleZoomControls:true,
  30. rotateControls: true,
  31. modal:false,
  32. customUploadButtonId:'',
  33. customSaveButtonId:'',
  34. loaderHtml:'',
  35. scaleToFill: true,
  36. processInline: false,
  37. loadPicture:'',
  38. onReset: null,
  39. enableMousescroll: false,
  40. colorAbsorption:false,
  41. //callbacks
  42. onBeforeImgUpload: null,
  43. onAfterImgUpload: null,
  44. onImgDrag: null,
  45. onImgZoom: null,
  46. onImgRotate: null,
  47. onBeforeImgCrop: null,
  48. onAfterImgCrop: null,
  49. onBeforeRemoveCroppedImg: null,
  50. onAfterRemoveCroppedImg: null,
  51. onError: null,
  52. };
  53. // OVERWRITE DEFAULT OPTIONS
  54. for (i in options) that.options[i] = options[i];
  55. // INIT THE WHOLE DAMN THING!!!
  56. that.init();
  57. };
  58. Croppic.prototype = {
  59. id:'',
  60. imgInitW:0,
  61. imgInitH:0,
  62. imgW:0,
  63. imgH:0,
  64. actualRotationImgW:0,
  65. actualRotationImgH:0,
  66. objW:0,
  67. objH:0,
  68. actualRotation: 0,
  69. windowW:0,
  70. windowH:$(window).height(),
  71. obj:{},
  72. outputDiv:{},
  73. outputUrlObj:{},
  74. img:{},
  75. defaultImg:{},
  76. croppedImg:{},
  77. imgEyecandy:{},
  78. form:{},
  79. iframeform: {},
  80. iframeobj: {},
  81. cropControlsUpload:{},
  82. cropControlsCrop:{},
  83. cropControlZoomMuchIn:{},
  84. cropControlZoomMuchOut:{},
  85. cropControlZoomIn:{},
  86. cropControlZoomOut:{},
  87. cropControlCrop:{},
  88. cropControlReset:{},
  89. cropControlRemoveCroppedImage:{},
  90. cropControlOriginal:{},
  91. modal:{},
  92. loader:{},
  93. cropSaveControl:{},
  94. ctx:{},
  95. imgName:'',
  96. init: function () {
  97. var that = this;
  98. that.objW = that.obj.width();
  99. that.objH = that.obj.height();
  100. // reset rotation
  101. that.actualRotation = 0;
  102. that.actualRotationImgH=0;
  103. that.actualRotationImgW=0;
  104. that.colorAbsorption=false;
  105. that.imgBackground="";
  106. that.ctx={};
  107. that.imgName='';
  108. if( $.isEmptyObject(that.defaultImg)){ that.defaultImg = that.obj.find('img'); }
  109. that.createImgUploadControls();
  110. if( $.isEmptyObject(that.options.loadPicture)){
  111. that.bindImgUploadControl();
  112. }else{
  113. that.loadExistingImage();
  114. }
  115. },
  116. createImgUploadControls: function(){
  117. var that = this;
  118. var cropControlUpload = '';
  119. if(that.options.customUploadButtonId ===''){ cropControlUpload = '<i class="cropControlUpload"></i>'; }
  120. var cropControlRemoveCroppedImage = '<i class="cropControlRemoveCroppedImage"></i>';
  121. var cropControlOriginal = '<i class="cropControlOriginal"></i>';
  122. if( $.isEmptyObject(that.croppedImg))
  123. {
  124. cropControlRemoveCroppedImage='';
  125. cropControlOriginal='';
  126. }
  127. if( !$.isEmptyObject(that.options.loadPicture)){ cropControlUpload='';}
  128. var html = '<div class="cropControls cropControlsUpload"> ' + cropControlUpload + cropControlOriginal + cropControlRemoveCroppedImage + ' </div>';
  129. that.outputDiv.append(html);
  130. that.cropControlsUpload = that.outputDiv.find('.cropControlsUpload');
  131. if(that.options.customUploadButtonId ===''){ that.imgUploadControl = that.outputDiv.find('.cropControlUpload'); }
  132. else{ that.imgUploadControl = $('#'+that.options.customUploadButtonId); that.imgUploadControl.show(); }
  133. if(that.options.customSaveButtonId !==''){
  134. that.cropSaveControl= $('#'+that.options.customSaveButtonId); that.cropSaveControl.hide();
  135. }
  136. if( !$.isEmptyObject(that.croppedImg)){
  137. that.cropControlRemoveCroppedImage = that.outputDiv.find('.cropControlRemoveCroppedImage');
  138. that.cropControlOriginal = that.outputDiv.find('.cropControlOriginal');
  139. }
  140. },
  141. bindImgUploadControl: function(){
  142. var that = this;
  143. // CREATE UPLOAD IMG FORM
  144. var formHtml = '<form class="' + that.id + '_imgUploadForm" style="visibility: hidden;"> <input type="file" name="img" id="' + that.id + '_imgUploadField"> </form>';
  145. that.outputDiv.append(formHtml);
  146. that.form = that.outputDiv.find('.'+that.id+'_imgUploadForm');
  147. // CREATE FALLBACK IE9 IFRAME
  148. var fileUploadId = that.CreateFallbackIframe();
  149. that.imgUploadControl.off('click');
  150. that.imgUploadControl.on('click',function(){
  151. if (fileUploadId === "") {
  152. that.form.find('input[type="file"]').trigger('click');
  153. } else {
  154. //Trigger iframe file input click, otherwise access restriction error
  155. that.iframeform.find('input[type="file"]').trigger('click');
  156. }
  157. });
  158. that.cropSaveControl.off('click');
  159. that.cropSaveControl.on('click',function(){
  160. that.destroy();
  161. window.location.href="https://wwww.croppic.com?"+that.saveImgUrl;
  162. });
  163. if( !$.isEmptyObject(that.croppedImg)){
  164. that.cropControlRemoveCroppedImage.on('click',function(){
  165. if (typeof (that.options.onBeforeRemoveCroppedImg) === typeof(Function)) {
  166. that.options.onBeforeRemoveCroppedImg.call(that);
  167. }
  168. var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
  169. '[确认] 使用当前图片\n\r' +
  170. '[取消] 重新选择图片');
  171. var width= that.imgInitW;
  172. var height= that.imgInitH;
  173. that.croppedImg.remove();
  174. that.croppedImg = {};
  175. $(this).hide();
  176. that.cropSaveControl.hide();
  177. that.cropControlOriginal.hide();
  178. if (typeof (that.options.onAfterRemoveCroppedImg) === typeof(Function)) {
  179. that.options.onAfterRemoveCroppedImg.call(that);
  180. }
  181. if( !$.isEmptyObject(that.defaultImg)){
  182. that.obj.append(that.defaultImg);
  183. }
  184. if(that.options.outputUrlId !== ''){ $('#'+that.options.outputUrlId).val(''); }
  185. that.imgUploadControl.show();
  186. if (res) {
  187. that.showLoader();
  188. that.imgUploadControl.hide();
  189. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  190. that.imgInitW = that.imgW = width;
  191. that.imgInitH = that.imgH = height;
  192. that.saveImgUrl="";
  193. that.obj.append('<img src="'+that.imgUrl+'">');
  194. that.initCropper();
  195. that.hideLoader();
  196. }
  197. });
  198. that.cropControlOriginal.on('click',function(){
  199. if (that.imgUrl=='')
  200. {
  201. alert('请选择图片' );
  202. return;
  203. }
  204. var res = confirm('您确定要使用原图吗?\n\r' +
  205. '[确认] 使用原图\n\r' +
  206. '[取消] 继续编辑');
  207. if (res) {
  208. that.destroy();
  209. window.location.href="https://wwww.croppic.com?"+that.imgUrl;
  210. }
  211. });
  212. }
  213. that.form.find('input[type="file"]').change(function(){
  214. if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
  215. that.showLoader();
  216. that.imgUploadControl.hide();
  217. if(that.options.processInline){
  218. // Checking Browser Support for FileReader API
  219. if (typeof FileReader == "undefined"){
  220. if (that.options.onError) that.options.onError.call(that,"processInline is not supported by your Browser");
  221. that.reset();
  222. }else{
  223. var file=that.form.find('input[type="file"]')[0].files[0];
  224. var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
  225. if (!rFilter.test(file.type)) {
  226. alert("请选择jpeg、png格式的图片");
  227. that.imgUploadControl.show();
  228. that.hideLoader();
  229. return;
  230. }
  231. if( !$.isEmptyObject(that.croppedImg)){
  232. that.destroy();
  233. }
  234. var Orientation = null;
  235. //获取照片方向角属性,用户旋转控制
  236. EXIF.getData(file, function() {
  237. EXIF.getAllTags(this);
  238. Orientation = EXIF.getTag(this, 'Orientation');
  239. });
  240. var reader = new FileReader();
  241. reader.onload = function (e) {
  242. if (Orientation!=null&&Orientation != "" && Orientation != 1
  243. &&(Orientation==8||Orientation==6||Orientation==3))
  244. {
  245. that.takingCorrect(e.target.result);
  246. reader.clear();
  247. reader.destroy();
  248. return;
  249. }
  250. var image = new Image();
  251. image.src = e.target.result;
  252. image.onload = function(){
  253. that.imgInitW = that.imgW = image.width;
  254. that.imgInitH = that.imgH = image.height;
  255. that.imgUrl=image.src;
  256. if(that.options.modal){ that.createModal(); }
  257. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  258. that.saveImgUrl="";
  259. that.obj.append('<img src="'+image.src+'">');
  260. that.initCropper();
  261. that.hideLoader();
  262. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  263. }
  264. };
  265. reader.readAsDataURL(file);
  266. }
  267. } else {
  268. try {
  269. // other modern browsers
  270. formData = new FormData(that.form[0]);
  271. } catch(e) {
  272. // IE10 MUST have all form items appended as individual form key / value pairs
  273. formData = new FormData();
  274. formData.append('img', that.form.find("input[type=file]")[0].files[0]);
  275. }
  276. for (var key in that.options.uploadData) {
  277. if( that.options.uploadData.hasOwnProperty(key) ) {
  278. formData.append( key , that.options.uploadData[key] );
  279. }
  280. }
  281. $.ajax({
  282. url: that.options.uploadUrl,
  283. data: formData,
  284. context: document.body,
  285. cache: false,
  286. contentType: false,
  287. processData: false,
  288. type: 'POST'
  289. }).always(function (data) {
  290. that.afterUpload(data);
  291. });
  292. }
  293. });
  294. },
  295. takingCorrect:function(file){
  296. // var that = this;
  297. // lrz(file,{quality:1}).then(function (rst) {
  298. // // console.log(rst.base64); //图片格式为base64;
  299. // var image = new Image();
  300. // image.src = rst.base64;
  301. // image.onload = function(){
  302. // that.imgInitW = that.imgW = image.width;
  303. // that.imgInitH = that.imgH = image.height;
  304. // that.imgUrl=image.src;
  305. // if(that.options.modal){ that.createModal(); }
  306. // if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  307. // that.saveImgUrl="";
  308. // that.obj.append('<img src="'+image.src+'">');
  309. // that.initCropper();
  310. // that.hideLoader();
  311. // if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  312. // }
  313. //
  314. // }) .catch(function (err) {
  315. // alert("打开图片失败");
  316. // // 处理失败会执行
  317. // }).always(function () {
  318. // // 不管是成功失败,都会执行
  319. // });
  320. var time = new Date(); // 程序计时的月从0开始取值后+1
  321. var m = time.getMonth() + 1;
  322. var t = time.getFullYear() + "-" + m + "-"
  323. + time.getDate() + " " + time.getHours() + ":"
  324. + time.getMinutes() + ":" + time.getSeconds();
  325. var meg='开始上传:'+t;
  326. var that = this;
  327. var formData = new FormData();
  328. var mime =that.getFileMime(file);
  329. formData.append("imgUrl", that.convertBase64UrlToBlob(file));
  330. var xhr = new XMLHttpRequest();
  331. xhr.open("POST", "taking",true);
  332. xhr.responseType = "blob";
  333. xhr.timeout = 60000*5;
  334. xhr.onload= function() {
  335. if (xhr.readyState === 4 && xhr.status === 200) {
  336. var blob = this.response;
  337. var Error=this.getResponseHeader("Content-My-Error");
  338. if (Error!=null)
  339. {
  340. var ErrorMeg=decodeURIComponent(atob(Error).split('').map(function (c) {
  341. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  342. }).join(''));
  343. if (that.options.onError) that.options.onError.call(that,ErrorMeg);
  344. that.imgUploadControl.show();
  345. that.hideLoader();
  346. return;
  347. }
  348. var filename=xhr.getResponseHeader("Content-My-filename");
  349. if (filename!=null)
  350. {
  351. that.imgName=filename;
  352. }
  353. meg=meg+" \n\r" +'上传完成准备处理:'+xhr.getResponseHeader("Content-My-start");
  354. meg=meg+" \n\r" +'处理完成准备下载:'+xhr.getResponseHeader("Content-My-end");
  355. var time2 = new Date(); // 程序计时的月从0开始取值后+1
  356. var m2 = time2.getMonth() + 1;
  357. var t2 = time2.getFullYear() + "-" + m + "-"
  358. + time2.getDate() + " " + time2.getHours() + ":"
  359. + time2.getMinutes() + ":" + time2.getSeconds();
  360. meg=meg+" \n\r" +'下载完成:'+t2;
  361. var reader = new FileReader();
  362. reader.onload = function (e) {
  363. var image = new Image();
  364. image.src = e.target.result;
  365. image.onload = function(){
  366. that.imgInitW = that.imgW = image.width;
  367. that.imgInitH = that.imgH = image.height;
  368. var arr = image.src.split(',');
  369. that.imgUrl= 'data:'+ mime+';base64,'+arr[1];
  370. if(that.options.modal){ that.createModal(); }
  371. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  372. that.saveImgUrl="";
  373. that.obj.append('<img src="'+ that.imgUrl+'">');
  374. that.initCropper();
  375. that.hideLoader();
  376. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  377. alert(meg);
  378. }
  379. }
  380. reader.readAsDataURL(blob);
  381. }else {
  382. if (that.options.onError) that.options.onError.call(that,"处理失败");
  383. that.imgUploadControl.show();
  384. that.hideLoader();
  385. }
  386. };
  387. xhr.send(formData);
  388. }
  389. ,loadExistingImage: function(){
  390. var that = this;
  391. if( $.isEmptyObject(that.croppedImg)){
  392. if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
  393. that.showLoader();
  394. if(that.options.modal){ that.createModal(); }
  395. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  396. that.imgUrl=that.options.loadPicture ;
  397. var img =$('<img src="'+ that.options.loadPicture +'">');
  398. that.obj.append(img);
  399. img.load(function() {
  400. that.imgInitW = that.imgW = this.width;
  401. that.imgInitH = that.imgH = this.height;
  402. that.initCropper();
  403. that.hideLoader();
  404. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  405. });
  406. }else{
  407. that.cropControlRemoveCroppedImage.on('click',function(){
  408. var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
  409. '[确认] 使用当前图片\n\r' +
  410. '[取消] 重新选择图片');
  411. var width= that.imgInitW;
  412. var height= that.imgInitH;
  413. that.croppedImg.remove();
  414. $(this).hide();
  415. that.cropSaveControl.hide();
  416. that.cropControlOriginal.hide();
  417. if( !$.isEmptyObject(that.defaultImg)){
  418. that.obj.append(that.defaultImg);
  419. }
  420. if(that.options.outputUrlId !== ''){ $('#'+that.options.outputUrlId).val(''); }
  421. that.croppedImg = '';
  422. that.reset();
  423. if (res) {
  424. that.showLoader();
  425. that.imgUploadControl.hide();
  426. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  427. that.imgInitW = that.imgW = width;
  428. that.imgInitH = that.imgH = height;
  429. that.saveImgUrl="";
  430. that.obj.append('<img src="'+that.imgUrl+'">');
  431. that.initCropper();
  432. that.hideLoader();
  433. }
  434. });
  435. }
  436. },
  437. afterUpload: function(data){
  438. var that = this;
  439. response = typeof data =='object' ? data : jQuery.parseJSON(data);
  440. if (response.status == 'success') {
  441. that.imgInitW = that.imgW = response.width;
  442. that.imgInitH = that.imgH = response.height;
  443. if (that.options.modal) { that.createModal(); }
  444. if (!$.isEmptyObject(that.croppedImg)) { that.croppedImg.remove(); }
  445. that.imgUrl = response.url;
  446. var img = $('<img src="'+response.url+'">')
  447. that.obj.append(img);
  448. img.load(function(){
  449. that.initCropper();
  450. that.hideLoader();
  451. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  452. });
  453. if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
  454. }
  455. if (response.status == 'error') {
  456. alert(response.message);
  457. if (that.options.onError) that.options.onError.call(that,response.message);
  458. that.hideLoader();
  459. // setTimeout( function(){ that.reset(); },2000)
  460. }
  461. },
  462. createModal: function(){
  463. var that = this;
  464. var marginTop = that.windowH/2-that.objH/2;
  465. var modalHTML = '<div id="croppicModal">'+'<div id="croppicModalObj" style="width:'+ that.objW +'px; height:'+ that.objH +'px; margin:0 auto; margin-top:'+ marginTop +'px; position: relative;"> </div>'+'</div>';
  466. $('body').append(modalHTML);
  467. that.modal = $('#croppicModal');
  468. that.obj = $('#croppicModalObj');
  469. },
  470. destroyModal: function(){
  471. var that = this;
  472. that.obj = that.outputDiv;
  473. that.modal.remove();
  474. that.modal = {};
  475. },
  476. initCropper: function(){
  477. var that = this;
  478. /*SET UP SOME VARS*/
  479. that.img = that.obj.find('img');
  480. that.img.wrap('<div class="cropImgWrapper" style="overflow:hidden; z-index:1; position:absolute; width:'+that.objW+'px; height:'+that.objH+'px;"></div>');
  481. /*INIT DRAGGING*/
  482. that.createCropControls();
  483. if(that.options.imgEyecandy){ that.createEyecandy(); }
  484. that.initDrag();
  485. that.initialScaleImg();
  486. },
  487. createEyecandy: function(){
  488. var that = this;
  489. that.imgEyecandy = that.img.clone();
  490. that.imgEyecandy.css({'z-index':'0','opacity':that.options.imgEyecandyOpacity}).appendTo(that.obj);
  491. },
  492. destroyEyecandy: function(){
  493. var that = this;
  494. that.imgEyecandy.remove();
  495. },
  496. initialScaleImg:function(){
  497. var that = this;
  498. that.zoom(0);
  499. that.zoom(that.options.initialZoom);
  500. // Adding mousewheel zoom capabilities
  501. if (that.options.enableMousescroll){
  502. that.img.on('mousewheel', function(event) {
  503. event.preventDefault();
  504. if (that.colorAbsorption)
  505. {
  506. return;
  507. }
  508. that.zoom(that.options.zoomFactor*event.deltaY);
  509. });
  510. }
  511. // initial center image
  512. that.img.css({'left': -(that.imgW -that.objW)/2, 'top': -(that.imgH -that.objH)/2, 'position':'relative'});
  513. if(that.options.imgEyecandy){ that.imgEyecandy.css({'left': -(that.imgW -that.objW)/2, 'top': -(that.imgH -that.objH)/2, 'position':'relative'}); }
  514. },
  515. createCropControls: function(){
  516. var that = this;
  517. // CREATE CONTROLS
  518. var cropControlZoomMuchIn = '';
  519. var cropControlZoomIn = '<i class="cropControlZoomIn"></i>';
  520. var cropControlZoomOut = '<i class="cropControlZoomOut"></i>';
  521. var cropControlZoomMuchOut = '';
  522. var cropControlRotateLeft = '';
  523. var cropControlRotateRight = '';
  524. var cropControlRotateMuchLeft = '';
  525. var cropControlRotateMuchRight = '';
  526. var cropControlCrop = '<i class="cropControlCrop"></i>';
  527. var cropControlReset = '<i class="cropControlReset"></i>';
  528. var cropControlOriginal = '<i class="cropControlOriginal"></i>';
  529. var cropControlXiColor = '<i class="cropControlXiColor"></i>';
  530. var cropControlXiColor2 = '<i class="cropControlXiColor2"></i>';
  531. var cropControlSetColor = '<i class="cropControlSetColor"></i>';
  532. var html;
  533. if(that.options.doubleZoomControls){
  534. cropControlZoomMuchIn = '<i class="cropControlZoomMuchIn"></i>';
  535. cropControlZoomMuchOut = '<i class="cropControlZoomMuchOut"></i>';
  536. }
  537. if(that.options.rotateControls){
  538. cropControlRotateLeft = '<i class="cropControlRotateLeft"></i>';
  539. cropControlRotateRight = '<i class="cropControlRotateRight"></i>';
  540. cropControlRotateMuchLeft = '<i class="cropControlRotateMuchLeft"></i>';
  541. cropControlRotateMuchRight = '<i class="cropControlRotateMuchRight"></i>';
  542. }
  543. html = '<div class="cropControls cropControlsCrop">'+ cropControlZoomMuchIn + cropControlZoomIn + cropControlZoomOut + cropControlZoomMuchOut
  544. + cropControlRotateMuchLeft+ cropControlRotateLeft + cropControlRotateRight + cropControlRotateMuchRight + cropControlCrop + '</div>';
  545. that.obj.append(html);
  546. html = '<div class="cropControls cropControlsCrop cropControlsUpload">' + cropControlXiColor2 + cropControlXiColor+ cropControlSetColor + cropControlOriginal + cropControlReset + '</div>';
  547. that.obj.append(html);
  548. that.cropControlsCrop = that.obj.find('.cropControlsCrop');
  549. // CACHE AND BIND CONTROLS
  550. if(that.options.doubleZoomControls){
  551. that.cropControlZoomMuchIn = that.cropControlsCrop.find('.cropControlZoomMuchIn');
  552. that.cropControlZoomMuchIn.on('click',function(){ that.zoom( that.options.zoomFactor*10 ); });
  553. that.cropControlZoomMuchOut = that.cropControlsCrop.find('.cropControlZoomMuchOut');
  554. that.cropControlZoomMuchOut.on('click',function(){ that.zoom(-that.options.zoomFactor*10); });
  555. }
  556. that.cropControlZoomIn = that.cropControlsCrop.find('.cropControlZoomIn');
  557. that.cropControlZoomIn.on('click',function(){ that.zoom(that.options.zoomFactor); });
  558. that.cropControlZoomOut = that.cropControlsCrop.find('.cropControlZoomOut');
  559. that.cropControlZoomOut.on('click',function(){ that.zoom(-that.options.zoomFactor); });
  560. that.cropControlRotateLeft = that.cropControlsCrop.find('.cropControlRotateLeft');
  561. that.cropControlRotateLeft.on('click', function() { that.rotate(-0.5);});
  562. that.cropControlRotateMuchLeft = that.cropControlsCrop.find('.cropControlRotateMuchLeft');
  563. that.cropControlRotateMuchLeft.on('click', function() { that.rotate(-10);});
  564. that.cropControlRotateRight = that.cropControlsCrop.find('.cropControlRotateRight');
  565. that.cropControlRotateRight.on('click', function() {that.rotate(0.5);});
  566. that.cropControlRotateMuchRight = that.cropControlsCrop.find('.cropControlRotateMuchRight');
  567. that.cropControlRotateMuchRight.on('click', function() {that.rotate(10);});
  568. that.cropControlCrop = that.cropControlsCrop.find('.cropControlCrop');
  569. that.cropControlCrop.on('click',function(){ that.crop(); });
  570. that.cropControlReset = that.cropControlsCrop.find('.cropControlReset');
  571. that.cropControlReset.on('click',function(){
  572. var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
  573. '[确认] 使用当前图片\n\r' +
  574. '[取消] 重新选择图片');
  575. var width= that.imgInitW;
  576. var height= that.imgInitH;
  577. that.reset();
  578. if (res) {
  579. that.showLoader();
  580. that.imgUploadControl.hide();
  581. if( !$.isEmptyObject(that.croppedImg)){ that.croppedImg.remove(); }
  582. that.imgInitW = that.imgW = width;
  583. that.imgInitH = that.imgH = height;
  584. that.saveImgUrl="";
  585. that.obj.append('<img src="'+that.imgUrl+'">');
  586. that.initCropper();
  587. that.hideLoader();
  588. }
  589. });
  590. that.cropControlOriginal = that.cropControlsCrop.find('.cropControlOriginal');
  591. that.cropControlOriginal.on('click',function(){
  592. if (that.imgUrl=='')
  593. {
  594. alert('请选择图片' );
  595. return;
  596. }
  597. var res = confirm('您确定要使用原图吗?\n\r' +
  598. '[确认] 使用原图\n\r' +
  599. '[取消] 继续编辑');
  600. if (res) {
  601. that.destroy();
  602. // prompt(that.imgUrl);
  603. window.location.href="https://wwww.croppic.com?"+that.imgUrl;
  604. }
  605. });
  606. that.cropControlXiColor = that.cropControlsCrop.find('.cropControlXiColor');
  607. that.cropControlXiColor.on('click',function(){that.colorOnClick(false);});
  608. that.cropControlXiColor2 = that.cropControlsCrop.find('.cropControlXiColor2');
  609. that.cropControlXiColor2.on('click',function(){that.colorOnClick(false);});
  610. that.cropControlSetColor= that.cropControlsCrop.find('.cropControlSetColor');
  611. that.cropControlSetColor.on('click',function(){that.colorOnClick(true);});
  612. that.colpick=that.cropControlSetColor.colpick({
  613. onSubmit:function(hsb,hex,rgb,el) {
  614. var background="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";
  615. that.obj.find('.cropImgWrapper').css('background',background);
  616. $(el).colpickHide();
  617. that.imgBackground=background;
  618. }
  619. });
  620. },
  621. colorOnClick:function(input)
  622. {
  623. var that = this;
  624. if (that.colorAbsorption||input)
  625. {
  626. that.cropControlsCrop.find('.cropControlXiColor').css("display","block");
  627. that.cropControlsCrop.find('.cropControlXiColor2').css("display","none");
  628. that.colorAbsorption=false;
  629. }else {
  630. that.cropControlsCrop.find('.cropControlXiColor').css("display","none");
  631. that.cropControlsCrop.find('.cropControlXiColor2').css("display","block");
  632. that.colorAbsorption=true;
  633. }
  634. },
  635. absorption:function(pageX,pageY){
  636. var that = this;
  637. that.showLoader();
  638. that.cropControlsCrop.hide();
  639. var cropData = {
  640. imgInitW:that.imgInitW,
  641. imgInitH:that.imgInitH,
  642. imgW:that.imgW,
  643. imgH:that.imgH,
  644. imgY1:parseInt( that.img.css('top') ),
  645. imgX1: parseInt( that.img.css('left')),
  646. cropH:that.objH,
  647. cropW:that.objW,
  648. rotation:that.actualRotation,
  649. pageX:pageX,
  650. pageY:pageY,
  651. imgBackground:that.imgBackground
  652. };
  653. var formData = new FormData();
  654. for (var key in cropData) {
  655. if( cropData.hasOwnProperty(key) ) {
  656. formData.append( key , cropData[key] );
  657. }
  658. }
  659. if (that.imgName=='')
  660. {
  661. formData.append("imgUrl", that.convertBase64UrlToBlob(that.imgUrl));
  662. }else {
  663. formData.append( "imgName" , that.imgName );
  664. }
  665. $.ajax({
  666. url: that.options.absorptionUrl,
  667. data: formData,
  668. cache: false,
  669. contentType: false,
  670. processData: false,
  671. type: 'POST'
  672. }).always(function (data) {
  673. var response;
  674. try {
  675. response = jQuery.parseJSON(data);
  676. }
  677. catch(err) {
  678. response = typeof data =='object' ? data : jQuery.parseJSON(data);
  679. }
  680. if (response.status == 'success') {
  681. that.imgName=response.imgName;
  682. var rgb={r:response.r,g:response.g,b:response.b};
  683. var background="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";
  684. that.obj.find('.cropImgWrapper').css("background",background);
  685. that.imgBackground=background;
  686. that.cropControlSetColor.colpickSetColor(rgb);
  687. }else if (response.status == 'error') {
  688. if (that.options.onError) that.options.onError.call(that,response.message);
  689. }else {
  690. if (that.options.onError) that.options.onError.call(that,"处理失败");
  691. }
  692. that.cropControlsCrop.show();
  693. that.hideLoader();
  694. });
  695. },
  696. initDrag:function(){
  697. var that = this;
  698. that.img.on("mousedown touchstart", function(e) {
  699. e.preventDefault(); // disable selection
  700. var pageX;
  701. var pageY;
  702. var userAgent = window.navigator.userAgent;
  703. if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/android/i) || (e.pageY && e.pageX) == undefined) {
  704. pageX = e.originalEvent.touches[0].pageX;
  705. pageY = e.originalEvent.touches[0].pageY;
  706. } else {
  707. pageX = e.pageX;
  708. pageY = e.pageY;
  709. }
  710. var z_idx = that.img.css('z-index'),
  711. drg_h = that.img.outerHeight(),
  712. drg_w = that.img.outerWidth(),
  713. pos_y = that.img.offset().top + drg_h - pageY,
  714. pos_x = that.img.offset().left + drg_w - pageX;
  715. that.z_idx=z_idx;
  716. that.drg_h=drg_h;
  717. that.drg_w=drg_w;
  718. that.pos_y=pos_y;
  719. that.pos_x=pos_x;
  720. if (that.colorAbsorption)
  721. {
  722. if (that.actualRotation!==0)
  723. {
  724. that.absorption(pageX-10,pageY-50);
  725. return;
  726. }
  727. var ml=that.imgInitW/that.imgW;
  728. var x = pageX-parseInt( that.img.css('left'))-10;
  729. var y = pageY-parseInt( that.img.css('top'))-50;
  730. x=parseInt(x*ml);
  731. y=parseInt(y*ml);
  732. if (!(x<0||x>that.imgInitW||y<0||y>that.imgInitH))
  733. {
  734. var imgData={};
  735. if( $.isEmptyObject(that.ctx))
  736. {
  737. var canvas = document.createElement("canvas");
  738. if (!canvas.getContext) {
  739. alert("浏览器版本太低无法使用吸色!");
  740. return;
  741. }
  742. that.ctx= canvas.getContext("2d");
  743. var newImg = new Image();
  744. newImg.onload = function(){
  745. canvas.width = that.imgInitW;
  746. canvas.height = that.imgInitH;
  747. that.ctx.drawImage(newImg, 0, 0);
  748. imgData = that.ctx.getImageData(x, y, 1, 1);
  749. var rgb = {r:imgData.data[0],g:imgData.data[1],b:imgData.data[2]};
  750. var background="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";
  751. that.obj.find('.cropImgWrapper').css("background",background);
  752. that.imgBackground=background;
  753. that.cropControlSetColor.colpickSetColor(rgb);
  754. }
  755. newImg.src = that.imgUrl;
  756. }else {
  757. imgData = that.ctx.getImageData(x, y, 1, 1);
  758. var rgb = {r:imgData.data[0],g:imgData.data[1],b:imgData.data[2]};
  759. var background="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";
  760. that.obj.find('.cropImgWrapper').css("background",background);
  761. that.imgBackground=background;
  762. that.cropControlSetColor.colpickSetColor(rgb);
  763. }
  764. }
  765. return;
  766. }
  767. }).on("mouseup", function() {
  768. that.img.off("mousemove");
  769. }).on("mouseout", function() {
  770. that.img.off("mousemove");
  771. });
  772. that.img.css('z-index', 1000).on("mousemove touchmove", function(e) {
  773. e.preventDefault();
  774. if (that.colorAbsorption)
  775. {
  776. return;
  777. }
  778. var z_idx=that.z_idx;
  779. var drg_h=that.drg_h;
  780. var drg_w=that.drg_w;
  781. var pos_y=that.pos_y;
  782. var pos_x=that.pos_x;
  783. var imgTop;
  784. var imgLeft;
  785. var userAgent = window.navigator.userAgent;
  786. if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/android/i) || (e.pageY && e.pageX) == undefined) {
  787. imgTop = e.originalEvent.touches[0].pageY + pos_y - drg_h;
  788. imgLeft = e.originalEvent.touches[0].pageX + pos_x - drg_w;
  789. } else {
  790. imgTop = e.pageY + pos_y - drg_h;
  791. imgLeft = e.pageX + pos_x - drg_w;
  792. }
  793. that.img.offset({
  794. top:imgTop,
  795. left:imgLeft
  796. }).on("mouseup", function() {
  797. $(this).removeClass('draggable').css('z-index', z_idx);
  798. });
  799. if(that.options.imgEyecandy){ that.imgEyecandy.offset({ top:imgTop, left:imgLeft }); }
  800. var top=that.actualRotationImgH;
  801. var left=that.actualRotationImgW;
  802. if (that.objH < that.imgH+top*2) {
  803. if (parseInt(that.img.css('top')) > top) { that.img.css('top', top); if (that.options.imgEyecandy) { that.imgEyecandy.css('top', top);}}
  804. var maxTop = -( that.imgH - that.objH+top); if (parseInt(that.img.css('top')) < maxTop) { that.img.css('top', maxTop); if (that.options.imgEyecandy) { that.imgEyecandy.css('top', maxTop); }}
  805. }else{
  806. if (parseInt(that.img.css('top')) < -top) { that.img.css('top', -top); if (that.options.imgEyecandy) { that.imgEyecandy.css('top', -top); }}
  807. var maxTop = that.objH - that.imgH+top; if (parseInt(that.img.css('top')) > maxTop) { that.img.css('top', maxTop);if (that.options.imgEyecandy) {that.imgEyecandy.css('top', maxTop); }}
  808. }
  809. if (that.objW < that.imgW+2*left) {
  810. if( parseInt( that.img.css('left')) > left ){ that.img.css('left',left); if(that.options.imgEyecandy){ that.imgEyecandy.css('left', left); }}
  811. var maxLeft = -( that.imgW-that.objW+left); if( parseInt( that.img.css('left')) < maxLeft){ that.img.css('left', maxLeft); if(that.options.imgEyecandy){ that.imgEyecandy.css('left', maxLeft); } }
  812. }else{
  813. if( parseInt( that.img.css('left')) < -left ){ that.img.css('left',-left); if(that.options.imgEyecandy){ that.imgEyecandy.css('left', -left); }}
  814. var maxLeft = ( that.objW - that.imgW+left); if( parseInt( that.img.css('left')) > maxLeft){ that.img.css('left', maxLeft); if(that.options.imgEyecandy){ that.imgEyecandy.css('left', maxLeft); } }
  815. }
  816. if (that.options.onImgDrag) that.options.onImgDrag.call(that);
  817. });
  818. },
  819. rotate: function(x) {
  820. var that = this;
  821. that.colorOnClick(true);
  822. that.actualRotation += x;
  823. that.img.css({
  824. '-webkit-transform': 'rotate(' + that.actualRotation + 'deg)',
  825. '-moz-transform': 'rotate(' + that.actualRotation + 'deg)',
  826. 'transform': 'rotate(' + that.actualRotation + 'deg)',
  827. });
  828. if(that.options.imgEyecandy) {
  829. that.imgEyecandy.css({
  830. '-webkit-transform': 'rotate(' + that.actualRotation + 'deg)',
  831. '-moz-transform': 'rotate(' + that.actualRotation + 'deg)',
  832. 'transform': 'rotate(' + that.actualRotation + 'deg)',
  833. });
  834. }
  835. that.actualRotationImgH=0;
  836. that.actualRotationImgW=0;
  837. if (that.actualRotation!=0)
  838. {
  839. var actualRotation=that.actualRotation%360;
  840. if (actualRotation<0)
  841. {
  842. actualRotation=0-actualRotation;
  843. }
  844. if (actualRotation==90||actualRotation==270)
  845. {
  846. if(that.imgH>that.imgW)
  847. {
  848. that.actualRotationImgW=parseInt((that.imgH-that.imgW)/2);
  849. }else if(that.imgH<that.imgW)
  850. {
  851. that.actualRotationImgH=parseInt((that.imgW-that.imgH)/2);
  852. }
  853. }else if (actualRotation!=180&&actualRotation!=360) {
  854. if (actualRotation>180)
  855. {
  856. actualRotation=actualRotation-180;
  857. }
  858. if (actualRotation>90)
  859. {
  860. actualRotation=180-actualRotation;
  861. }
  862. var radian = Math.sin(actualRotation * Math.PI / 180);
  863. that.actualRotationImgW=parseInt(radian*(that.imgH)/2);
  864. that.actualRotationImgH=parseInt(radian*(that.imgW)/2);
  865. }
  866. }
  867. if (typeof that.options.onImgRotate == 'function')
  868. that.options.onImgRotate.call(that);
  869. },
  870. zoom :function(x){
  871. var that = this;
  872. that.colorOnClick(true);
  873. var ratio = that.imgW / that.imgH;
  874. var newWidth = that.imgW+x;
  875. var newHeight = newWidth/ratio;
  876. var doPositioning = true;
  877. if (x==0)
  878. {
  879. if( newWidth - that.objW < newHeight - that.objH ){
  880. newWidth = that.objW;
  881. newHeight = newWidth/ratio;
  882. }else{
  883. newHeight = that.objH;
  884. newWidth = ratio * newHeight;
  885. }
  886. }
  887. if( newWidth < that.objW || newHeight < that.objH){
  888. doPositioning = false;
  889. }
  890. if(!that.options.scaleToFill && (newWidth > that.imgInitW || newHeight > that.imgInitH)){
  891. doPositioning = false;
  892. }
  893. that.imgW = newWidth;
  894. that.img.width(newWidth);
  895. that.imgH = newHeight;
  896. that.img.height(newHeight);
  897. var newTop = parseInt( that.img.css('top') ) - x/2;
  898. var newLeft = parseInt( that.img.css('left') ) - x/2;
  899. that.actualRotationImgH=0;
  900. that.actualRotationImgW=0;
  901. if (that.actualRotation!=0)
  902. {
  903. var actualRotation=that.actualRotation%360;
  904. if (actualRotation<0)
  905. {
  906. actualRotation=0-actualRotation;
  907. }
  908. if (actualRotation==90||actualRotation==270)
  909. {
  910. if(that.imgH>that.imgW)
  911. {
  912. that.actualRotationImgW=parseInt((that.imgH-that.imgW)/2);
  913. }else if(that.imgH<that.imgW)
  914. {
  915. that.actualRotationImgH=parseInt((that.imgW-that.imgH)/2);
  916. }
  917. }else if (actualRotation!=180&&actualRotation!=360) {
  918. if (actualRotation>180)
  919. {
  920. actualRotation=actualRotation-180;
  921. }
  922. if (actualRotation>90)
  923. {
  924. actualRotation=180-actualRotation;
  925. }
  926. var radian = Math.sin(actualRotation * Math.PI / 180);
  927. that.actualRotationImgW=parseInt(radian*(that.imgH)/2);
  928. that.actualRotationImgH=parseInt(radian*(that.imgW)/2);
  929. }
  930. }
  931. if( newTop>-that.actualRotationImgH ){ newTop=-that.actualRotationImgH;}
  932. if( newLeft>-that.actualRotationImgW ){ newLeft=-that.actualRotationImgW;}
  933. var maxTop = -( newHeight-that.objH+that.actualRotationImgH); if( newTop < maxTop){ newTop = maxTop; }
  934. var maxLeft = -( newWidth-that.objW+that.actualRotationImgW); if( newLeft < maxLeft){ newLeft = maxLeft; }
  935. if( doPositioning ){
  936. that.img.css({'top':newTop, 'left':newLeft});
  937. }
  938. if(that.options.imgEyecandy){
  939. that.imgEyecandy.width(newWidth);
  940. that.imgEyecandy.height(newHeight);
  941. if( doPositioning ){
  942. that.imgEyecandy.css({'top':newTop, 'left':newLeft});
  943. }
  944. }
  945. if (that.options.onImgZoom) that.options.onImgZoom.call(that);
  946. },
  947. crop:function(){
  948. var that = this;
  949. that.colorOnClick(true);
  950. if (that.options.onBeforeImgCrop) that.options.onBeforeImgCrop.call(that);
  951. that.cropControlsCrop.hide();
  952. that.showLoader();
  953. var cropData = {
  954. imgInitW:that.imgInitW,
  955. imgInitH:that.imgInitH,
  956. imgW:that.imgW,
  957. imgH:that.imgH,
  958. imgY1:parseInt( that.img.css('top') ),
  959. imgX1: parseInt( that.img.css('left')),
  960. cropH:that.objH,
  961. cropW:that.objW,
  962. rotation:that.actualRotation,
  963. imgBackground:that.imgBackground
  964. };
  965. var formData = new FormData();
  966. for (var key in cropData) {
  967. if( cropData.hasOwnProperty(key) ) {
  968. formData.append( key , cropData[key] );
  969. }
  970. }
  971. for (var key in that.options.cropData) {
  972. if( that.options.cropData.hasOwnProperty(key) ) {
  973. formData.append( key , that.options.cropData[key] );
  974. }
  975. }
  976. if (that.imgName=='')
  977. {
  978. formData.append("imgUrl", that.convertBase64UrlToBlob(that.imgUrl));
  979. }else {
  980. formData.append( "imgName" , that.imgName );
  981. }
  982. var xhr = new XMLHttpRequest();
  983. xhr.open("POST", that.options.cropUrl);
  984. xhr.responseType = "blob";
  985. xhr.timeout = 60000*5;
  986. xhr.onload= function() {
  987. that.afterCrop(xhr);
  988. };
  989. xhr.send(formData);
  990. },
  991. convertBase64UrlToBlob:function (urlData) {
  992. var arr = urlData.split(',');
  993. var mime = arr[0].match(/:(.*?);/)[1];
  994. var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
  995. //处理异常,将ascii码小于0的转换为大于0
  996. var ab = new ArrayBuffer(bytes.length);
  997. var ia = new Uint8Array(ab);
  998. for (var i = 0; i < bytes.length; i++) {
  999. ia[i] = bytes.charCodeAt(i);
  1000. }
  1001. return new Blob([ab], { type: mime });
  1002. },
  1003. getFileMime:function (urlData) {
  1004. var arr = urlData.split(',');
  1005. return arr[0].match(/:(.*?);/)[1];
  1006. },
  1007. getFileExt:function (urlData) {
  1008. var arr = urlData.split(',');
  1009. var mime = arr[0].match(/:(.*?);/)[1];
  1010. var FileExt;
  1011. switch (mime)
  1012. {
  1013. case "image/jpeg":
  1014. FileExt="jpg";
  1015. break;
  1016. case "image/png":
  1017. FileExt="png";
  1018. break;
  1019. case "image/gif":
  1020. FileExt="gif";
  1021. break;
  1022. default:
  1023. FileExt="jpg";
  1024. }
  1025. return FileExt;
  1026. },
  1027. afterCrop: function (xhr) {
  1028. var that = this;
  1029. if (xhr.readyState === 4 && xhr.status === 200) {
  1030. var Error=xhr.getResponseHeader("Content-My-Error");
  1031. if (Error!=null)
  1032. {
  1033. var ErrorMeg=decodeURIComponent(atob(Error).split('').map(function (c) {
  1034. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1035. }).join(''));
  1036. if (that.options.onError) that.options.onError.call(that,ErrorMeg);
  1037. that.cropControlsCrop.show();
  1038. that.hideLoader();
  1039. return;
  1040. }
  1041. if (that.options.imgEyecandy)
  1042. that.imgEyecandy.hide();
  1043. var filename=xhr.getResponseHeader("Content-My-filename");
  1044. var blob = xhr.response;
  1045. var reader = new FileReader();
  1046. reader.onload = function (e) {
  1047. that.destroy();
  1048. that.saveImgUrl='product_image_crop_md5,'+filename+','+e.target.result;
  1049. var croppedImg='<img class="croppedImg" src="' + e.target.result + '">';
  1050. that.obj.append(croppedImg);
  1051. if (that.options.outputUrlId !== '') { $('#' + that.options.outputUrlId).val(response.url); }
  1052. that.croppedImg = that.obj.find('.croppedImg');
  1053. that.croppedImg .width(that.objW+"px").height(that.objH+"px");
  1054. that.init();
  1055. that.hideLoader();
  1056. that.imgUploadControl.hide();
  1057. that.cropSaveControl.show();
  1058. }
  1059. reader.readAsDataURL(blob);
  1060. }else {
  1061. if (that.options.onError) that.options.onError.call(that,"处理失败");
  1062. that.hideLoader();
  1063. that.cropControlsCrop.show();
  1064. }
  1065. if (that.options.onAfterImgCrop) that.options.onAfterImgCrop.call(that, response);
  1066. },
  1067. showLoader:function(){
  1068. var that = this;
  1069. that.obj.append(that.options.loaderHtml);
  1070. that.loader = that.obj.find('.loader');
  1071. },
  1072. hideLoader:function(){
  1073. var that = this;
  1074. that.loader.remove();
  1075. },
  1076. reset:function(){
  1077. var that = this;
  1078. that.destroy();
  1079. that.init();
  1080. that.imgUploadControl.show();
  1081. if( !$.isEmptyObject(that.croppedImg)){
  1082. that.obj.append(that.croppedImg);
  1083. if(that.options.outputUrlId !== ''){ $('#'+that.options.outputUrlId).val(that.croppedImg.attr('url')); }
  1084. }
  1085. if (typeof that.options.onReset == 'function')
  1086. that.options.onReset.call(that);
  1087. },
  1088. destroy:function(){
  1089. var that = this;
  1090. that.colorOnClick(true);
  1091. if(that.options.modal && !$.isEmptyObject(that.modal) ){ that.destroyModal(); }
  1092. if(that.options.imgEyecandy && !$.isEmptyObject(that.imgEyecandy) ){ that.destroyEyecandy(); }
  1093. if( !$.isEmptyObject( that.cropControlsUpload ) ){ that.cropControlsUpload.remove(); }
  1094. if( !$.isEmptyObject( that.cropControlsCrop ) ){ that.cropControlsCrop.remove(); }
  1095. if( !$.isEmptyObject( that.loader ) ){ that.loader.remove(); }
  1096. if( !$.isEmptyObject( that.form ) ){ that.form.remove(); }
  1097. that.obj.html('');
  1098. },
  1099. isAjaxUploadSupported: function () {
  1100. var input = document.createElement("input");
  1101. input.type = "file";
  1102. return (
  1103. "multiple" in input &&
  1104. typeof File != "undefined" &&
  1105. typeof FormData != "undefined" &&
  1106. typeof (new XMLHttpRequest()).upload != "undefined");
  1107. },
  1108. CreateFallbackIframe: function () {
  1109. var that = this;
  1110. if (!that.isAjaxUploadSupported()) {
  1111. if (jQuery.isEmptyObject(that.iframeobj)) {
  1112. var iframe = document.createElement("iframe");
  1113. iframe.setAttribute("id", that.id + "_upload_iframe");
  1114. iframe.setAttribute("name", that.id + "_upload_iframe");
  1115. iframe.setAttribute("width", "0");
  1116. iframe.setAttribute("height", "0");
  1117. iframe.setAttribute("border", "0");
  1118. iframe.setAttribute("src", "javascript:false;");
  1119. iframe.style.display = "none";
  1120. document.body.appendChild(iframe);
  1121. } else {
  1122. iframe = that.iframeobj[0];
  1123. }
  1124. var myContent = '<!DOCTYPE html>'
  1125. + '<html><head><title>Uploading File</title></head>'
  1126. + '<body>'
  1127. + '<form '
  1128. + 'class="' + that.id + '_upload_iframe_form" '
  1129. + 'name="' + that.id + '_upload_iframe_form" '
  1130. + 'action="' + that.options.uploadUrl + '" method="post" '
  1131. + 'enctype="multipart/form-data" encoding="multipart/form-data" style="display:none;">'
  1132. + $("#" + that.id + '_imgUploadField')[0].outerHTML
  1133. + '</form></body></html>';
  1134. iframe.contentWindow.document.open('text/htmlreplace');
  1135. iframe.contentWindow.document.write(myContent);
  1136. iframe.contentWindow.document.close();
  1137. that.iframeobj = $("#" + that.id + "_upload_iframe");
  1138. that.iframeform = that.iframeobj.contents().find("html").find("." + that.id + "_upload_iframe_form");
  1139. that.iframeform.on("change", "input", function () {
  1140. that.SubmitFallbackIframe(that);
  1141. });
  1142. that.iframeform.find("input")[0].attachEvent("onchange", function () {
  1143. that.SubmitFallbackIframe(that);
  1144. });
  1145. var eventHandlermyFile = function () {
  1146. if (iframe.detachEvent)
  1147. iframe.detachEvent("onload", eventHandlermyFile);
  1148. else
  1149. iframe.removeEventListener("load", eventHandlermyFile, false);
  1150. var response = that.getIframeContentJSON(iframe);
  1151. if (jQuery.isEmptyObject(that.modal)) {
  1152. that.afterUpload(response);
  1153. }
  1154. }
  1155. if (iframe.addEventListener)
  1156. iframe.addEventListener("load", eventHandlermyFile, true);
  1157. if (iframe.attachEvent)
  1158. iframe.attachEvent("onload", eventHandlermyFile);
  1159. return "#" + that.id + '_imgUploadField';
  1160. } else {
  1161. return "";
  1162. }
  1163. },
  1164. SubmitFallbackIframe: function (that) {
  1165. that.showLoader();
  1166. if(that.options.processInline && !that.options.uploadUrl){
  1167. if (that.options.onError){
  1168. that.options.onError.call(that,"processInline is not supported by your browser ");
  1169. that.hideLoader();
  1170. }
  1171. }else{
  1172. if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
  1173. that.iframeform[0].submit();
  1174. }
  1175. },
  1176. getIframeContentJSON: function (iframe) {
  1177. try {
  1178. var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document,
  1179. response;
  1180. var innerHTML = doc.body.innerHTML;
  1181. if (innerHTML.slice(0, 5).toLowerCase() == "<pre>" && innerHTML.slice(-6).toLowerCase() == "</pre>") {
  1182. innerHTML = doc.body.firstChild.firstChild.nodeValue;
  1183. }
  1184. response = jQuery.parseJSON(innerHTML);
  1185. } catch (err) {
  1186. response = { success: false };
  1187. }
  1188. return response;
  1189. },
  1190. hexadecimal:function(num) {
  1191. var r = parseInt(num).toString(16);
  1192. if (r.length == 1) {
  1193. return '0' + r;
  1194. }
  1195. return r.toUpperCase();
  1196. }
  1197. };
  1198. })(window, document);