123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611 |
- /*
- * CROPPIC
- * dependancy: jQuery
- * author: Ognjen "Zmaj Džedaj" Božičković and Mat Steinlin
- */
- (function (window, document) {
- Croppic = function (id, options) {
- var that = this;
- that.id = id;
- that.obj = $('#' + id);
- that.outputDiv = that.obj;
- that.imgUrl = "";
- that.saveImgUrl = "";
- that.imgBackground = "";
- // DEFAULT OPTIONS
- that.options = {
- uploadUrl: '',
- uploadData: {},
- cropUrl: '',
- cropData: {},
- outputUrlId: '',
- absorptionUrl: '',
- //styles
- imgEyecandy: true,
- imgEyecandyOpacity: 0.2,
- initialZoom: 40,
- zoomFactor: 10,
- rotateFactor: 5,
- doubleZoomControls: true,
- rotateControls: true,
- modal: false,
- customUploadButtonId: '',
- customSaveButtonId: '',
- loaderHtml: '',
- scaleToFill: true,
- processInline: false,
- loadPicture: '',
- onReset: null,
- enableMousescroll: false,
- colorAbsorption: false,
- //callbacks
- onBeforeImgUpload: null,
- onAfterImgUpload: null,
- onImgDrag: null,
- onImgZoom: null,
- onImgRotate: null,
- onBeforeImgCrop: null,
- onAfterImgCrop: null,
- onBeforeRemoveCroppedImg: null,
- onAfterRemoveCroppedImg: null,
- onError: null,
- };
- // OVERWRITE DEFAULT OPTIONS
- for (i in options) that.options[i] = options[i];
- // INIT THE WHOLE DAMN THING!!!
- that.init();
- };
- Croppic.prototype = {
- id: '',
- imgInitW: 0,
- imgInitH: 0,
- imgW: 0,
- imgH: 0,
- actualRotationImgW: 0,
- actualRotationImgH: 0,
- objW: 0,
- objH: 0,
- actualRotation: 0,
- windowW: 0,
- windowH: $(window).height(),
- obj: {},
- outputDiv: {},
- outputUrlObj: {},
- img: {},
- defaultImg: {},
- croppedImg: {},
- imgEyecandy: {},
- form: {},
- iframeform: {},
- iframeobj: {},
- cropControlsUpload: {},
- cropControlsCrop: {},
- cropControlZoomMuchIn: {},
- cropControlZoomMuchOut: {},
- cropControlZoomIn: {},
- cropControlZoomOut: {},
- cropControlCrop: {},
- cropControlReset: {},
- cropControlRemoveCroppedImage: {},
- cropControlOriginal: {},
- modal: {},
- loader: {},
- cropSaveControl: {},
- ctx: {},
- imgName: '',
- init: function () {
- var that = this;
- that.objW = that.obj.width();
- that.objH = that.obj.height();
- // reset rotation
- that.actualRotation = 0;
- that.actualRotationImgH = 0;
- that.actualRotationImgW = 0;
- that.colorAbsorption = false;
- that.imgBackground = "";
- that.ctx = {};
- that.imgName = '';
- if ($.isEmptyObject(that.defaultImg)) {
- that.defaultImg = that.obj.find('img');
- }
- that.createImgUploadControls();
- if ($.isEmptyObject(that.options.loadPicture)) {
- that.bindImgUploadControl();
- } else {
- that.loadExistingImage();
- }
- },
- createImgUploadControls: function () {
- var that = this;
- var cropControlUpload = '';
- if (that.options.customUploadButtonId === '') {
- cropControlUpload = '<i class="cropControlUpload"></i>';
- }
- var cropControlRemoveCroppedImage = '<i class="cropControlRemoveCroppedImage"></i>';
- var cropControlOriginal = '<i class="cropControlOriginal"></i>';
- if ($.isEmptyObject(that.croppedImg)) {
- cropControlRemoveCroppedImage = '';
- cropControlOriginal = '';
- }
- if (!$.isEmptyObject(that.options.loadPicture)) {
- cropControlUpload = '';
- }
- var html = '<div class="cropControls cropControlsUpload"> ' + cropControlUpload + cropControlOriginal + cropControlRemoveCroppedImage + ' </div>';
- that.outputDiv.append(html);
- that.cropControlsUpload = that.outputDiv.find('.cropControlsUpload');
- if (that.options.customUploadButtonId === '') {
- that.imgUploadControl = that.outputDiv.find('.cropControlUpload');
- }
- else {
- that.imgUploadControl = $('#' + that.options.customUploadButtonId);
- that.imgUploadControl.show();
- }
- if (that.options.customSaveButtonId !== '') {
- that.cropSaveControl = $('#' + that.options.customSaveButtonId);
- that.cropSaveControl.hide();
- }
- if (!$.isEmptyObject(that.croppedImg)) {
- that.cropControlRemoveCroppedImage = that.outputDiv.find('.cropControlRemoveCroppedImage');
- that.cropControlOriginal = that.outputDiv.find('.cropControlOriginal');
- }
- },
- bindImgUploadControl: function () {
- var that = this;
- // CREATE UPLOAD IMG FORM
- var formHtml = '<form class="' + that.id + '_imgUploadForm" style="visibility: hidden;"> <input type="file" name="img" id="' + that.id + '_imgUploadField"> </form>';
- that.outputDiv.append(formHtml);
- that.form = that.outputDiv.find('.' + that.id + '_imgUploadForm');
- // CREATE FALLBACK IE9 IFRAME
- var fileUploadId = that.CreateFallbackIframe();
- that.imgUploadControl.off('click');
- that.imgUploadControl.on('click', function () {
- if (fileUploadId === "") {
- that.form.find('input[type="file"]').trigger('click');
- } else {
- //Trigger iframe file input click, otherwise access restriction error
- that.iframeform.find('input[type="file"]').trigger('click');
- }
- });
- that.cropSaveControl.off('click');
- that.cropSaveControl.on('click', function () {
- that.destroy();
- window.location.href = "https://wwww.croppic.com?" + that.saveImgUrl;
- });
- if (!$.isEmptyObject(that.croppedImg)) {
- that.cropControlRemoveCroppedImage.on('click', function () {
- if (typeof (that.options.onBeforeRemoveCroppedImg) === typeof(Function)) {
- that.options.onBeforeRemoveCroppedImg.call(that);
- }
- var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
- '[确认] 使用当前图片\n\r' +
- '[取消] 重新选择图片');
- var width = that.imgInitW;
- var height = that.imgInitH;
- that.croppedImg.remove();
- that.croppedImg = {};
- $(this).hide();
- that.cropSaveControl.hide();
- that.cropControlOriginal.hide();
- if (typeof (that.options.onAfterRemoveCroppedImg) === typeof(Function)) {
- that.options.onAfterRemoveCroppedImg.call(that);
- }
- if (!$.isEmptyObject(that.defaultImg)) {
- that.obj.append(that.defaultImg);
- }
- if (that.options.outputUrlId !== '') {
- $('#' + that.options.outputUrlId).val('');
- }
- that.imgUploadControl.show();
- if (res) {
- that.showLoader();
- that.imgUploadControl.hide();
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.imgInitW = that.imgW = width;
- that.imgInitH = that.imgH = height;
- that.saveImgUrl = "";
- that.obj.append('<img src="' + that.imgUrl + '">');
- that.initCropper();
- that.hideLoader();
- }
- });
- that.cropControlOriginal.on('click', function () {
- if (that.imgUrl == '') {
- alert('请选择图片');
- return;
- }
- var res = confirm('您确定要使用原图吗?\n\r' +
- '[确认] 使用原图\n\r' +
- '[取消] 继续编辑');
- if (res) {
- // that.destroy();
- // window.location.href = "https://wwww.croppic.com?" + that.imgUrl;
- that.controlOriginal();
- }
- });
- }
- that.form.find('input[type="file"]').change(function () {
- if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
- that.showLoader();
- that.imgUploadControl.hide();
- if (that.options.processInline) {
- // Checking Browser Support for FileReader API
- if (typeof FileReader == "undefined") {
- if (that.options.onError) that.options.onError.call(that, "processInline is not supported by your Browser");
- that.reset();
- } else {
- var file = that.form.find('input[type="file"]')[0].files[0];
- var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
- if (!rFilter.test(file.type)) {
- alert("请选择jpeg、png格式的图片");
- that.imgUploadControl.show();
- that.hideLoader();
- return;
- }
- if (!$.isEmptyObject(that.croppedImg)) {
- that.destroy();
- }
- var Orientation = null;
- //获取照片方向角属性,用户旋转控制
- EXIF.getData(file, function () {
- EXIF.getAllTags(this);
- Orientation = EXIF.getTag(this, 'Orientation');
- // $('#exif').html(EXIF.pretty(this));
- // $('#exif').html(Orientation);
- });
- var reader = new FileReader();
- reader.onload = function (e) {
- if (Orientation != null && Orientation != "" && Orientation != 1
- && (Orientation == 8 || Orientation == 6 || Orientation == 3)) {
- that.takingCorrectJs2(e.target.result,Orientation);
- reader.clear();
- reader.destroy();
- return;
- }
- var image = new Image();
- image.src = e.target.result;
- image.onload = function () {
- that.imgInitW = that.imgW = image.width;
- that.imgInitH = that.imgH = image.height;
- that.imgUrl = image.src;
- if (that.options.modal) {
- that.createModal();
- }
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.saveImgUrl = "";
- that.obj.append('<img src="' + image.src + '">');
- that.initCropper();
- that.hideLoader();
- if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
- }
- };
- reader.readAsDataURL(file);
- }
- } else {
- try {
- // other modern browsers
- formData = new FormData(that.form[0]);
- } catch (e) {
- // IE10 MUST have all form items appended as individual form key / value pairs
- formData = new FormData();
- formData.append('img', that.form.find("input[type=file]")[0].files[0]);
- }
- for (var key in that.options.uploadData) {
- if (that.options.uploadData.hasOwnProperty(key)) {
- formData.append(key, that.options.uploadData[key]);
- }
- }
- $.ajax({
- url: that.options.uploadUrl,
- data: formData,
- context: document.body,
- cache: false,
- contentType: false,
- processData: false,
- type: 'POST'
- }).always(function (data) {
- that.afterUpload(data);
- });
- }
- });
- },
- takingCorrectJs: function (file) {
- var that = this;
- lrz(file, {quality: 1}).then(function (rst) {
- // console.log(rst.base64); //图片格式为base64;
- var image = new Image();
- image.src = rst.base64;
- image.onload = function () {
- that.imgInitW = that.imgW = image.width;
- that.imgInitH = that.imgH = image.height;
- that.imgUrl = image.src;
- if (that.options.modal) {
- that.createModal();
- }
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.saveImgUrl = "";
- that.obj.append('<img src="' + image.src + '">');
- that.initCropper();
- that.hideLoader();
- if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
- }
- }).catch(function (err) {
- alert("打开图片失败");
- // 处理失败会执行
- }).always(function () {
- // 不管是成功失败,都会执行
- });
- },
- // 此方法是旋转图片;
- takingCorrectJs2: function (img, dir) {
- var that = this;
- var image = new Image();
- image.onload = function () {
- var degree = 0, drawWidth, drawHeight, width, height;
- drawWidth = this.naturalWidth;
- drawHeight = this.naturalHeight;
- //以下改变一下图片大小
- // var maxSide = Math.max(drawWidth, drawHeight);
- // if (maxSide > 3072) {
- // var minSide = Math.min(drawWidth, drawHeight);
- // minSide = minSide / maxSide * 3072;
- // maxSide = 3072;
- // if (drawWidth > drawHeight) {
- // drawWidth = maxSide;
- // drawHeight = minSide;
- // } else {
- // drawWidth = minSide;
- // drawHeight = maxSide;
- // }
- // }
- var canvas = document.createElement('canvas');
- canvas.width = width = drawWidth;
- canvas.height = height = drawHeight;
- var context = canvas.getContext('2d');
- //判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
- switch (dir) {
- //iphone横屏拍摄,此时home键在左侧
- case 3:
- degree = 180;
- drawWidth = -width;
- drawHeight = -height;
- break;
- //iphone竖屏拍摄,此时home键在下方(正常拿手机的方向)
- case 6:
- canvas.width = height;
- canvas.height = width;
- degree = 90;
- drawWidth = width;
- drawHeight = -height;
- break;
- //iphone竖屏拍摄,此时home键在上方
- case 8:
- canvas.width = height;
- canvas.height = width;
- degree = 270;
- drawWidth = -width;
- drawHeight = height;
- break;
- }
- //使用canvas旋转校正
- context.rotate(degree * Math.PI / 180);
- context.drawImage(this, 0, 0, drawWidth, drawHeight);
- // 判断图片 类型 (可增加判断的类型 此处只判断了 jpeg 和png)
- var imgtype = img.includes('image/png') ? "image/png" : "image/jpeg";
- //返回校正图片
- var imageNext = new Image();
- imageNext.onload = function () {
- that.imgInitW = that.imgW = imageNext.width;
- that.imgInitH = that.imgH = imageNext.height;
- that.imgUrl = imageNext.src;
- if (that.options.modal) {
- that.createModal();
- }
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.saveImgUrl = "";
- that.obj.append('<img src="' + imageNext.src + '">');
- that.initCropper();
- that.hideLoader();
- if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
- }
- imageNext.src = canvas.toDataURL(imgtype, 1);
- }
- image.src = img;
- },
- controlOriginal: function () {
- var that = this;
- that.showLoader();
- that.cropControlsCrop.hide();
- var formData = new FormData();
- formData.append("uploadOriginal","1");
- if (that.imgName != undefined&&that.imgName!=null&&that.imgName.length>0)
- {
- formData.append("imgName", that.imgName);
- }else {
- formData.append("imgUrl", that.convertBase64UrlToBlob(that.imgUrl));
- }
- $.ajax({
- url: that.options.absorptionUrl,
- data: formData,
- cache: false,
- contentType: false,
- processData: false,
- type: 'POST'
- }).always(function (data) {
- // if (that.options.onError) that.options.onError.call(that,JSON.stringify(data));
- var response;
- try {
- response = jQuery.parseJSON(data);
- }
- catch (err) {
- response = typeof data == 'object' ? data : jQuery.parseJSON(data);
- }
- if (response.status == 'success') {
- that.imgName = response.imgName;
- that.destroy();
- // prompt(that.imgUrl);
- window.location.href = "https://wwww.croppic.com?" +'product_image_crop_md5,' + that.imgName + ','+ that.imgUrl;
- return;
- } else if (response.status == 'error') {
- if (that.options.onError) that.options.onError.call(that, response.message);
- } else {
- if (that.options.onError) that.options.onError.call(that, "处理失败");
- }
- that.cropControlsCrop.show();
- that.hideLoader();
- });
- },
- takingCorrect: function (file) {
- var time = new Date(); // 程序计时的月从0开始取值后+1
- var t = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
- var meg = '开始上传:' + t;
- var that = this;
- var formData = new FormData();
- var mime = that.getFileMime(file);
- formData.append("imgUrl", that.convertBase64UrlToBlob(file));
- var xhr = new XMLHttpRequest();
- xhr.open("POST", "taking", true);
- xhr.responseType = "blob";
- xhr.timeout = 60000 * 5;
- xhr.onload = function () {
- if (xhr.readyState === 4 && xhr.status === 200) {
- var blob = this.response;
- var Error = this.getResponseHeader("Content-My-Error");
- if (Error != null) {
- var ErrorMeg = decodeURIComponent(atob(Error).split('').map(function (c) {
- return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
- }).join(''));
- if (that.options.onError) that.options.onError.call(that, ErrorMeg);
- that.imgUploadControl.show();
- that.hideLoader();
- return;
- }
- var filename = xhr.getResponseHeader("Content-My-filename");
- if (filename != null) {
- that.imgName = filename;
- meg = meg + " \n\r" + '上传完成准备处理:' + xhr.getResponseHeader("Content-My-start");
- meg = meg + " \n\r" + '处理完成准备下载:' + xhr.getResponseHeader("Content-My-end");
- var time2 = new Date(); // 程序计时的月从0开始取值后+1
- var t2 = time2.getHours() + ":" + time2.getMinutes() + ":" + time2.getSeconds();
- meg = meg + " \n\r" + '下载完成:' + t2;
- }
- var reader = new FileReader();
- reader.onload = function (e) {
- var image = new Image();
- image.src = e.target.result;
- image.onload = function () {
- that.imgInitW = that.imgW = image.width;
- that.imgInitH = that.imgH = image.height;
- var arr = image.src.split(',');
- that.imgUrl = 'data:' + mime + ';base64,' + arr[1];
- if (that.options.modal) {
- that.createModal();
- }
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.saveImgUrl = "";
- that.obj.append('<img src="' + that.imgUrl + '">');
- that.initCropper();
- that.hideLoader();
- if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
- // alert(meg);
- }
- }
- reader.readAsDataURL(blob);
- } else {
- if (that.options.onError) that.options.onError.call(that, "处理失败,错误代码["+xhr.readyState+"]");
- that.imgUploadControl.show();
- that.hideLoader();
- }
- };
- xhr.send(formData);
- }
- , loadExistingImage: function () {
- var that = this;
- if ($.isEmptyObject(that.croppedImg)) {
- if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
- that.showLoader();
- if (that.options.modal) {
- that.createModal();
- }
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.imgUrl = that.options.loadPicture;
- var img = $('<img src="' + that.options.loadPicture + '">');
- that.obj.append(img);
- img.load(function () {
- that.imgInitW = that.imgW = this.width;
- that.imgInitH = that.imgH = this.height;
- that.initCropper();
- that.hideLoader();
- if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
- });
- } else {
- that.cropControlRemoveCroppedImage.on('click', function () {
- var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
- '[确认] 使用当前图片\n\r' +
- '[取消] 重新选择图片');
- var width = that.imgInitW;
- var height = that.imgInitH;
- that.croppedImg.remove();
- $(this).hide();
- that.cropSaveControl.hide();
- that.cropControlOriginal.hide();
- if (!$.isEmptyObject(that.defaultImg)) {
- that.obj.append(that.defaultImg);
- }
- if (that.options.outputUrlId !== '') {
- $('#' + that.options.outputUrlId).val('');
- }
- that.croppedImg = '';
- that.reset();
- if (res) {
- that.showLoader();
- that.imgUploadControl.hide();
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.imgInitW = that.imgW = width;
- that.imgInitH = that.imgH = height;
- that.saveImgUrl = "";
- that.obj.append('<img src="' + that.imgUrl + '">');
- that.initCropper();
- that.hideLoader();
- }
- });
- }
- },
- afterUpload: function (data) {
- var that = this;
- response = typeof data == 'object' ? data : jQuery.parseJSON(data);
- if (response.status == 'success') {
- that.imgInitW = that.imgW = response.width;
- that.imgInitH = that.imgH = response.height;
- if (that.options.modal) {
- that.createModal();
- }
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.imgUrl = response.url;
- var img = $('<img src="' + response.url + '">')
- that.obj.append(img);
- img.load(function () {
- that.initCropper();
- that.hideLoader();
- if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
- });
- if (that.options.onAfterImgUpload) that.options.onAfterImgUpload.call(that);
- }
- if (response.status == 'error') {
- alert(response.message);
- if (that.options.onError) that.options.onError.call(that, response.message);
- that.hideLoader();
- // setTimeout( function(){ that.reset(); },2000)
- }
- },
- createModal: function () {
- var that = this;
- var marginTop = that.windowH / 2 - that.objH / 2;
- 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>';
- $('body').append(modalHTML);
- that.modal = $('#croppicModal');
- that.obj = $('#croppicModalObj');
- },
- destroyModal: function () {
- var that = this;
- that.obj = that.outputDiv;
- that.modal.remove();
- that.modal = {};
- },
- initCropper: function () {
- var that = this;
- /*SET UP SOME VARS*/
- that.img = that.obj.find('img');
- that.img.wrap('<div class="cropImgWrapper" style="overflow:hidden; z-index:1; position:absolute; width:' + that.objW + 'px; height:' + that.objH + 'px;"></div>');
- /*INIT DRAGGING*/
- that.createCropControls();
- if (that.options.imgEyecandy) {
- that.createEyecandy();
- }
- that.initDrag();
- that.initialScaleImg();
- },
- createEyecandy: function () {
- var that = this;
- that.imgEyecandy = that.img.clone();
- that.imgEyecandy.css({'z-index': '0', 'opacity': that.options.imgEyecandyOpacity}).appendTo(that.obj);
- },
- destroyEyecandy: function () {
- var that = this;
- that.imgEyecandy.remove();
- },
- initialScaleImg: function () {
- var that = this;
- that.zoom(0);
- that.zoom(that.options.initialZoom);
- // Adding mousewheel zoom capabilities
- if (that.options.enableMousescroll) {
- that.img.on('mousewheel', function (event) {
- event.preventDefault();
- if (that.colorAbsorption) {
- return;
- }
- that.zoom(that.options.zoomFactor * event.deltaY);
- });
- }
- // initial center image
- that.img.css({
- 'left': -(that.imgW - that.objW) / 2,
- 'top': -(that.imgH - that.objH) / 2,
- 'position': 'relative'
- });
- if (that.options.imgEyecandy) {
- that.imgEyecandy.css({
- 'left': -(that.imgW - that.objW) / 2,
- 'top': -(that.imgH - that.objH) / 2,
- 'position': 'relative'
- });
- }
- },
- createCropControls: function () {
- var that = this;
- // CREATE CONTROLS
- var cropControlZoomMuchIn = '';
- var cropControlZoomIn = '<i class="cropControlZoomIn"></i>';
- var cropControlZoomOut = '<i class="cropControlZoomOut"></i>';
- var cropControlZoomMuchOut = '';
- var cropControlRotateLeft = '';
- var cropControlRotateRight = '';
- var cropControlRotateMuchLeft = '';
- var cropControlRotateMuchRight = '';
- var cropControlCrop = '<i class="cropControlCrop"></i>';
- var cropControlReset = '<i class="cropControlReset"></i>';
- var cropControlOriginal = '<i class="cropControlOriginal"></i>';
- var cropControlXiColor = '<i class="cropControlXiColor"></i>';
- var cropControlXiColor2 = '<i class="cropControlXiColor2"></i>';
- var cropControlSetColor = '<i class="cropControlSetColor"></i>';
- var html;
- if (that.options.doubleZoomControls) {
- cropControlZoomMuchIn = '<i class="cropControlZoomMuchIn"></i>';
- cropControlZoomMuchOut = '<i class="cropControlZoomMuchOut"></i>';
- }
- if (that.options.rotateControls) {
- cropControlRotateLeft = '<i class="cropControlRotateLeft"></i>';
- cropControlRotateRight = '<i class="cropControlRotateRight"></i>';
- cropControlRotateMuchLeft = '<i class="cropControlRotateMuchLeft"></i>';
- cropControlRotateMuchRight = '<i class="cropControlRotateMuchRight"></i>';
- }
- html = '<div class="cropControls cropControlsCrop">' + cropControlZoomMuchIn + cropControlZoomIn + cropControlZoomOut + cropControlZoomMuchOut
- + cropControlRotateMuchLeft + cropControlRotateLeft + cropControlRotateRight + cropControlRotateMuchRight + cropControlCrop + '</div>';
- that.obj.append(html);
- html = '<div class="cropControls cropControlsCrop cropControlsUpload">' + cropControlXiColor2 + cropControlXiColor + cropControlSetColor + cropControlOriginal + cropControlReset + '</div>';
- that.obj.append(html);
- that.cropControlsCrop = that.obj.find('.cropControlsCrop');
- // CACHE AND BIND CONTROLS
- if (that.options.doubleZoomControls) {
- that.cropControlZoomMuchIn = that.cropControlsCrop.find('.cropControlZoomMuchIn');
- that.cropControlZoomMuchIn.on('click', function () {
- that.zoom(that.options.zoomFactor * 10);
- });
- that.cropControlZoomMuchOut = that.cropControlsCrop.find('.cropControlZoomMuchOut');
- that.cropControlZoomMuchOut.on('click', function () {
- that.zoom(-that.options.zoomFactor * 10);
- });
- }
- that.cropControlZoomIn = that.cropControlsCrop.find('.cropControlZoomIn');
- that.cropControlZoomIn.on('click', function () {
- that.zoom(that.options.zoomFactor);
- });
- that.cropControlZoomOut = that.cropControlsCrop.find('.cropControlZoomOut');
- that.cropControlZoomOut.on('click', function () {
- that.zoom(-that.options.zoomFactor);
- });
- that.cropControlRotateLeft = that.cropControlsCrop.find('.cropControlRotateLeft');
- that.cropControlRotateLeft.on('click', function () {
- that.rotate(-0.5);
- });
- that.cropControlRotateMuchLeft = that.cropControlsCrop.find('.cropControlRotateMuchLeft');
- that.cropControlRotateMuchLeft.on('click', function () {
- that.rotate(-10);
- });
- that.cropControlRotateRight = that.cropControlsCrop.find('.cropControlRotateRight');
- that.cropControlRotateRight.on('click', function () {
- that.rotate(0.5);
- });
- that.cropControlRotateMuchRight = that.cropControlsCrop.find('.cropControlRotateMuchRight');
- that.cropControlRotateMuchRight.on('click', function () {
- that.rotate(10);
- });
- that.cropControlCrop = that.cropControlsCrop.find('.cropControlCrop');
- that.cropControlCrop.on('click', function () {
- that.crop();
- });
- that.cropControlReset = that.cropControlsCrop.find('.cropControlReset');
- that.cropControlReset.on('click', function () {
- var res = confirm('您是要使用当前图片还是重新选择图片?\n\r' +
- '[确认] 使用当前图片\n\r' +
- '[取消] 重新选择图片');
- var width = that.imgInitW;
- var height = that.imgInitH;
- that.reset();
- if (res) {
- that.showLoader();
- that.imgUploadControl.hide();
- if (!$.isEmptyObject(that.croppedImg)) {
- that.croppedImg.remove();
- }
- that.imgInitW = that.imgW = width;
- that.imgInitH = that.imgH = height;
- that.saveImgUrl = "";
- that.obj.append('<img src="' + that.imgUrl + '">');
- that.initCropper();
- that.hideLoader();
- }
- });
- that.cropControlOriginal = that.cropControlsCrop.find('.cropControlOriginal');
- that.cropControlOriginal.on('click', function () {
- if (that.imgUrl == '') {
- alert('请选择图片');
- return;
- }
- var res = confirm('您确定要使用原图吗?\n\r' +
- '[确认] 使用原图\n\r' +
- '[取消] 继续编辑');
- if (res) {
- // that.destroy();
- // window.location.href = "https://wwww.croppic.com?" + that.imgUrl;
- that.controlOriginal();
- }
- });
- that.cropControlXiColor = that.cropControlsCrop.find('.cropControlXiColor');
- that.cropControlXiColor.on('click', function () {
- that.colorOnClick(false);
- });
- that.cropControlXiColor2 = that.cropControlsCrop.find('.cropControlXiColor2');
- that.cropControlXiColor2.on('click', function () {
- that.colorOnClick(false);
- });
- that.cropControlSetColor = that.cropControlsCrop.find('.cropControlSetColor');
- that.cropControlSetColor.on('click', function () {
- that.colorOnClick(true);
- });
- that.colpick = that.cropControlSetColor.colpick({
- onSubmit: function (hsb, hex, rgb, el) {
- var background = "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
- that.obj.find('.cropImgWrapper').css('background', background);
- $(el).colpickHide();
- that.imgBackground = background;
- }
- });
- },
- colorOnClick: function (input) {
- var that = this;
- if (that.colorAbsorption || input) {
- that.cropControlsCrop.find('.cropControlXiColor').css("display", "block");
- that.cropControlsCrop.find('.cropControlXiColor2').css("display", "none");
- that.colorAbsorption = false;
- } else {
- that.cropControlsCrop.find('.cropControlXiColor').css("display", "none");
- that.cropControlsCrop.find('.cropControlXiColor2').css("display", "block");
- that.colorAbsorption = true;
- }
- },
- absorption: function (pageX, pageY) {
- var that = this;
- that.showLoader();
- that.cropControlsCrop.hide();
- var cropData = {
- imgInitW: that.imgInitW,
- imgInitH: that.imgInitH,
- imgW: that.imgW,
- imgH: that.imgH,
- imgY1: parseInt(that.img.css('top')),
- imgX1: parseInt(that.img.css('left')),
- cropH: that.objH,
- cropW: that.objW,
- rotation: that.actualRotation,
- pageX: pageX,
- pageY: pageY,
- imgBackground: that.imgBackground
- };
- var formData = new FormData();
- for (var key in cropData) {
- if (cropData.hasOwnProperty(key)) {
- formData.append(key, cropData[key]);
- }
- }
- if (that.imgName == '') {
- formData.append("imgUrl", that.convertBase64UrlToBlob(that.imgUrl));
- } else {
- formData.append("imgName", that.imgName);
- }
- $.ajax({
- url: that.options.absorptionUrl,
- data: formData,
- cache: false,
- contentType: false,
- processData: false,
- type: 'POST'
- }).always(function (data) {
- var response;
- try {
- response = jQuery.parseJSON(data);
- }
- catch (err) {
- response = typeof data == 'object' ? data : jQuery.parseJSON(data);
- }
- if (response.status == 'success') {
- that.imgName = response.imgName;
- var rgb = {r: response.r, g: response.g, b: response.b};
- var background = "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
- that.obj.find('.cropImgWrapper').css("background", background);
- that.imgBackground = background;
- that.cropControlSetColor.colpickSetColor(rgb);
- } else if (response.status == 'error') {
- if (that.options.onError) that.options.onError.call(that, response.message);
- } else {
- if (that.options.onError) that.options.onError.call(that, "处理失败");
- }
- that.cropControlsCrop.show();
- that.hideLoader();
- });
- },
- initDrag: function () {
- var that = this;
- that.img.on("mousedown touchstart", function (e) {
- e.preventDefault(); // disable selection
- var pageX;
- var pageY;
- var userAgent = window.navigator.userAgent;
- if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/android/i) || (e.pageY && e.pageX) == undefined) {
- pageX = e.originalEvent.touches[0].pageX;
- pageY = e.originalEvent.touches[0].pageY;
- } else {
- pageX = e.pageX;
- pageY = e.pageY;
- }
- var z_idx = that.img.css('z-index'),
- drg_h = that.img.outerHeight(),
- drg_w = that.img.outerWidth(),
- pos_y = that.img.offset().top + drg_h - pageY,
- pos_x = that.img.offset().left + drg_w - pageX;
- that.z_idx = z_idx;
- that.drg_h = drg_h;
- that.drg_w = drg_w;
- that.pos_y = pos_y;
- that.pos_x = pos_x;
- if (that.colorAbsorption) {
- if (that.actualRotation !== 0) {
- that.absorption(pageX - 10, pageY - 50);
- return;
- }
- var ml = that.imgInitW / that.imgW;
- var x = pageX - parseInt(that.img.css('left')) - 10;
- var y = pageY - parseInt(that.img.css('top')) - 50;
- x = parseInt(x * ml);
- y = parseInt(y * ml);
- if (!(x < 0 || x > that.imgInitW || y < 0 || y > that.imgInitH)) {
- var imgData = {};
- if ($.isEmptyObject(that.ctx)) {
- var canvas = document.createElement("canvas");
- if (!canvas.getContext) {
- alert("浏览器版本太低无法使用吸色!");
- return;
- }
- that.ctx = canvas.getContext("2d");
- var newImg = new Image();
- newImg.onload = function () {
- canvas.width = that.imgInitW;
- canvas.height = that.imgInitH;
- that.ctx.drawImage(newImg, 0, 0);
- imgData = that.ctx.getImageData(x, y, 1, 1);
- var rgb = {r: imgData.data[0], g: imgData.data[1], b: imgData.data[2]};
- var background = "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
- that.obj.find('.cropImgWrapper').css("background", background);
- that.imgBackground = background;
- that.cropControlSetColor.colpickSetColor(rgb);
- }
- newImg.src = that.imgUrl;
- } else {
- imgData = that.ctx.getImageData(x, y, 1, 1);
- var rgb = {r: imgData.data[0], g: imgData.data[1], b: imgData.data[2]};
- var background = "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
- that.obj.find('.cropImgWrapper').css("background", background);
- that.imgBackground = background;
- that.cropControlSetColor.colpickSetColor(rgb);
- }
- }
- return;
- }
- }).on("mouseup", function () {
- that.img.off("mousemove");
- }).on("mouseout", function () {
- that.img.off("mousemove");
- });
- that.img.css('z-index', 1000).on("mousemove touchmove", function (e) {
- e.preventDefault();
- if (that.colorAbsorption) {
- return;
- }
- var z_idx = that.z_idx;
- var drg_h = that.drg_h;
- var drg_w = that.drg_w;
- var pos_y = that.pos_y;
- var pos_x = that.pos_x;
- var imgTop;
- var imgLeft;
- var userAgent = window.navigator.userAgent;
- if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/android/i) || (e.pageY && e.pageX) == undefined) {
- imgTop = e.originalEvent.touches[0].pageY + pos_y - drg_h;
- imgLeft = e.originalEvent.touches[0].pageX + pos_x - drg_w;
- } else {
- imgTop = e.pageY + pos_y - drg_h;
- imgLeft = e.pageX + pos_x - drg_w;
- }
- that.img.offset({
- top: imgTop,
- left: imgLeft
- }).on("mouseup", function () {
- $(this).removeClass('draggable').css('z-index', z_idx);
- });
- if (that.options.imgEyecandy) {
- that.imgEyecandy.offset({top: imgTop, left: imgLeft});
- }
- var top = that.actualRotationImgH;
- var left = that.actualRotationImgW;
- if (that.objH < that.imgH + top * 2) {
- if (parseInt(that.img.css('top')) > top) {
- that.img.css('top', top);
- if (that.options.imgEyecandy) {
- that.imgEyecandy.css('top', top);
- }
- }
- 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);
- }
- }
- } else {
- if (parseInt(that.img.css('top')) < -top) {
- that.img.css('top', -top);
- if (that.options.imgEyecandy) {
- that.imgEyecandy.css('top', -top);
- }
- }
- 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);
- }
- }
- }
- if (that.objW < that.imgW + 2 * left) {
- if (parseInt(that.img.css('left')) > left) {
- that.img.css('left', left);
- if (that.options.imgEyecandy) {
- that.imgEyecandy.css('left', left);
- }
- }
- 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);
- }
- }
- } else {
- if (parseInt(that.img.css('left')) < -left) {
- that.img.css('left', -left);
- if (that.options.imgEyecandy) {
- that.imgEyecandy.css('left', -left);
- }
- }
- 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);
- }
- }
- }
- if (that.options.onImgDrag) that.options.onImgDrag.call(that);
- });
- },
- rotate: function (x) {
- var that = this;
- that.colorOnClick(true);
- that.actualRotation += x;
- that.img.css({
- '-webkit-transform': 'rotate(' + that.actualRotation + 'deg)',
- '-moz-transform': 'rotate(' + that.actualRotation + 'deg)',
- 'transform': 'rotate(' + that.actualRotation + 'deg)',
- });
- if (that.options.imgEyecandy) {
- that.imgEyecandy.css({
- '-webkit-transform': 'rotate(' + that.actualRotation + 'deg)',
- '-moz-transform': 'rotate(' + that.actualRotation + 'deg)',
- 'transform': 'rotate(' + that.actualRotation + 'deg)',
- });
- }
- that.actualRotationImgH = 0;
- that.actualRotationImgW = 0;
- if (that.actualRotation != 0) {
- var actualRotation = that.actualRotation % 360;
- if (actualRotation < 0) {
- actualRotation = 0 - actualRotation;
- }
- if (actualRotation == 90 || actualRotation == 270) {
- if (that.imgH > that.imgW) {
- that.actualRotationImgW = parseInt((that.imgH - that.imgW) / 2);
- } else if (that.imgH < that.imgW) {
- that.actualRotationImgH = parseInt((that.imgW - that.imgH) / 2);
- }
- } else if (actualRotation != 180 && actualRotation != 360) {
- if (actualRotation > 180) {
- actualRotation = actualRotation - 180;
- }
- if (actualRotation > 90) {
- actualRotation = 180 - actualRotation;
- }
- var radian = Math.sin(actualRotation * Math.PI / 180);
- that.actualRotationImgW = parseInt(radian * (that.imgH) / 2);
- that.actualRotationImgH = parseInt(radian * (that.imgW) / 2);
- }
- }
- if (typeof that.options.onImgRotate == 'function')
- that.options.onImgRotate.call(that);
- },
- zoom: function (x) {
- var that = this;
- that.colorOnClick(true);
- var ratio = that.imgW / that.imgH;
- var newWidth = that.imgW + x;
- var newHeight = newWidth / ratio;
- var doPositioning = true;
- if (x == 0) {
- if (newWidth - that.objW < newHeight - that.objH) {
- newWidth = that.objW;
- newHeight = newWidth / ratio;
- } else {
- newHeight = that.objH;
- newWidth = ratio * newHeight;
- }
- }
- if (newWidth < that.objW || newHeight < that.objH) {
- doPositioning = false;
- }
- if (!that.options.scaleToFill && (newWidth > that.imgInitW || newHeight > that.imgInitH)) {
- doPositioning = false;
- }
- that.imgW = newWidth;
- that.img.width(newWidth);
- that.imgH = newHeight;
- that.img.height(newHeight);
- var newTop = parseInt(that.img.css('top')) - x / 2;
- var newLeft = parseInt(that.img.css('left')) - x / 2;
- that.actualRotationImgH = 0;
- that.actualRotationImgW = 0;
- if (that.actualRotation != 0) {
- var actualRotation = that.actualRotation % 360;
- if (actualRotation < 0) {
- actualRotation = 0 - actualRotation;
- }
- if (actualRotation == 90 || actualRotation == 270) {
- if (that.imgH > that.imgW) {
- that.actualRotationImgW = parseInt((that.imgH - that.imgW) / 2);
- } else if (that.imgH < that.imgW) {
- that.actualRotationImgH = parseInt((that.imgW - that.imgH) / 2);
- }
- } else if (actualRotation != 180 && actualRotation != 360) {
- if (actualRotation > 180) {
- actualRotation = actualRotation - 180;
- }
- if (actualRotation > 90) {
- actualRotation = 180 - actualRotation;
- }
- var radian = Math.sin(actualRotation * Math.PI / 180);
- that.actualRotationImgW = parseInt(radian * (that.imgH) / 2);
- that.actualRotationImgH = parseInt(radian * (that.imgW) / 2);
- }
- }
- if (newTop > -that.actualRotationImgH) {
- newTop = -that.actualRotationImgH;
- }
- if (newLeft > -that.actualRotationImgW) {
- newLeft = -that.actualRotationImgW;
- }
- var maxTop = -(newHeight - that.objH + that.actualRotationImgH);
- if (newTop < maxTop) {
- newTop = maxTop;
- }
- var maxLeft = -(newWidth - that.objW + that.actualRotationImgW);
- if (newLeft < maxLeft) {
- newLeft = maxLeft;
- }
- if (doPositioning) {
- that.img.css({'top': newTop, 'left': newLeft});
- }
- if (that.options.imgEyecandy) {
- that.imgEyecandy.width(newWidth);
- that.imgEyecandy.height(newHeight);
- if (doPositioning) {
- that.imgEyecandy.css({'top': newTop, 'left': newLeft});
- }
- }
- if (that.options.onImgZoom) that.options.onImgZoom.call(that);
- },
- crop: function () {
- var that = this;
- that.colorOnClick(true);
- if (that.options.onBeforeImgCrop) that.options.onBeforeImgCrop.call(that);
- that.cropControlsCrop.hide();
- that.showLoader();
- var cropData = {
- imgInitW: that.imgInitW,
- imgInitH: that.imgInitH,
- imgW: that.imgW,
- imgH: that.imgH,
- imgY1: parseInt(that.img.css('top')),
- imgX1: parseInt(that.img.css('left')),
- cropH: that.objH,
- cropW: that.objW,
- rotation: that.actualRotation,
- imgBackground: that.imgBackground
- };
- var formData = new FormData();
- for (var key in cropData) {
- if (cropData.hasOwnProperty(key)) {
- formData.append(key, cropData[key]);
- }
- }
- for (var key in that.options.cropData) {
- if (that.options.cropData.hasOwnProperty(key)) {
- formData.append(key, that.options.cropData[key]);
- }
- }
- if (that.imgName == '') {
- formData.append("imgUrl", that.convertBase64UrlToBlob(that.imgUrl));
- } else {
- formData.append("imgName", that.imgName);
- }
- var xhr = new XMLHttpRequest();
- xhr.open("POST", that.options.cropUrl);
- xhr.responseType = "blob";
- xhr.timeout = 60000 * 5;
- xhr.onload = function () {
- that.afterCrop(xhr);
- };
- xhr.send(formData);
- },
- convertBase64UrlToBlob: function (urlData) {
- var arr = urlData.split(',');
- var mime = arr[0].match(/:(.*?);/)[1];
- var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
- //处理异常,将ascii码小于0的转换为大于0
- var ab = new ArrayBuffer(bytes.length);
- var ia = new Uint8Array(ab);
- for (var i = 0; i < bytes.length; i++) {
- ia[i] = bytes.charCodeAt(i);
- }
- return new Blob([ab], {type: mime});
- },
- getFileMime: function (urlData) {
- var arr = urlData.split(',');
- return arr[0].match(/:(.*?);/)[1];
- },
- getFileExt: function (urlData) {
- var arr = urlData.split(',');
- var mime = arr[0].match(/:(.*?);/)[1];
- var FileExt;
- switch (mime) {
- case "image/jpeg":
- FileExt = "jpg";
- break;
- case "image/png":
- FileExt = "png";
- break;
- case "image/gif":
- FileExt = "gif";
- break;
- default:
- FileExt = "jpg";
- }
- return FileExt;
- },
- afterCrop: function (xhr) {
- var that = this;
- if (xhr.readyState === 4 && xhr.status === 200) {
- var Error = xhr.getResponseHeader("Content-My-Error");
- if (Error != null) {
- var ErrorMeg = decodeURIComponent(atob(Error).split('').map(function (c) {
- return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
- }).join(''));
- if (that.options.onError) that.options.onError.call(that, ErrorMeg);
- that.cropControlsCrop.show();
- that.hideLoader();
- return;
- }
- if (that.options.imgEyecandy)
- that.imgEyecandy.hide();
- var filename = xhr.getResponseHeader("Content-My-filename");
- var blob = xhr.response;
- var reader = new FileReader();
- reader.onload = function (e) {
- that.destroy();
- that.saveImgUrl = 'product_image_crop_md5,' + filename + ',' + e.target.result;
- var croppedImg = '<img class="croppedImg" src="' + e.target.result + '">';
- that.obj.append(croppedImg);
- if (that.options.outputUrlId !== '') {
- $('#' + that.options.outputUrlId).val(response.url);
- }
- that.croppedImg = that.obj.find('.croppedImg');
- that.croppedImg.width(that.objW + "px").height(that.objH + "px");
- that.init();
- that.hideLoader();
- that.imgUploadControl.hide();
- that.cropSaveControl.show();
- }
- reader.readAsDataURL(blob);
- } else {
- if (that.options.onError) that.options.onError.call(that, "处理失败,错误代码["+xhr.readyState+"]=>"+ xhr.response.messageerror);
- that.hideLoader();
- that.cropControlsCrop.show();
- }
- if (that.options.onAfterImgCrop) that.options.onAfterImgCrop.call(that, xhr.response);
- },
- showLoader: function () {
- var that = this;
- that.obj.append(that.options.loaderHtml);
- that.loader = that.obj.find('.loader');
- },
- hideLoader: function () {
- var that = this;
- that.loader.remove();
- },
- reset: function () {
- var that = this;
- that.destroy();
- that.init();
- that.imgUploadControl.show();
- if (!$.isEmptyObject(that.croppedImg)) {
- that.obj.append(that.croppedImg);
- if (that.options.outputUrlId !== '') {
- $('#' + that.options.outputUrlId).val(that.croppedImg.attr('url'));
- }
- }
- if (typeof that.options.onReset == 'function')
- that.options.onReset.call(that);
- },
- destroy: function () {
- var that = this;
- that.colorOnClick(true);
- if (that.options.modal && !$.isEmptyObject(that.modal)) {
- that.destroyModal();
- }
- if (that.options.imgEyecandy && !$.isEmptyObject(that.imgEyecandy)) {
- that.destroyEyecandy();
- }
- if (!$.isEmptyObject(that.cropControlsUpload)) {
- that.cropControlsUpload.remove();
- }
- if (!$.isEmptyObject(that.cropControlsCrop)) {
- that.cropControlsCrop.remove();
- }
- if (!$.isEmptyObject(that.loader)) {
- that.loader.remove();
- }
- if (!$.isEmptyObject(that.form)) {
- that.form.remove();
- }
- that.obj.html('');
- },
- isAjaxUploadSupported: function () {
- var input = document.createElement("input");
- input.type = "file";
- return (
- "multiple" in input &&
- typeof File != "undefined" &&
- typeof FormData != "undefined" &&
- typeof (new XMLHttpRequest()).upload != "undefined");
- },
- CreateFallbackIframe: function () {
- var that = this;
- if (!that.isAjaxUploadSupported()) {
- if (jQuery.isEmptyObject(that.iframeobj)) {
- var iframe = document.createElement("iframe");
- iframe.setAttribute("id", that.id + "_upload_iframe");
- iframe.setAttribute("name", that.id + "_upload_iframe");
- iframe.setAttribute("width", "0");
- iframe.setAttribute("height", "0");
- iframe.setAttribute("border", "0");
- iframe.setAttribute("src", "javascript:false;");
- iframe.style.display = "none";
- document.body.appendChild(iframe);
- } else {
- iframe = that.iframeobj[0];
- }
- var myContent = '<!DOCTYPE html>'
- + '<html><head><title>Uploading File</title></head>'
- + '<body>'
- + '<form '
- + 'class="' + that.id + '_upload_iframe_form" '
- + 'name="' + that.id + '_upload_iframe_form" '
- + 'action="' + that.options.uploadUrl + '" method="post" '
- + 'enctype="multipart/form-data" encoding="multipart/form-data" style="display:none;">'
- + $("#" + that.id + '_imgUploadField')[0].outerHTML
- + '</form></body></html>';
- iframe.contentWindow.document.open('text/htmlreplace');
- iframe.contentWindow.document.write(myContent);
- iframe.contentWindow.document.close();
- that.iframeobj = $("#" + that.id + "_upload_iframe");
- that.iframeform = that.iframeobj.contents().find("html").find("." + that.id + "_upload_iframe_form");
- that.iframeform.on("change", "input", function () {
- that.SubmitFallbackIframe(that);
- });
- that.iframeform.find("input")[0].attachEvent("onchange", function () {
- that.SubmitFallbackIframe(that);
- });
- var eventHandlermyFile = function () {
- if (iframe.detachEvent)
- iframe.detachEvent("onload", eventHandlermyFile);
- else
- iframe.removeEventListener("load", eventHandlermyFile, false);
- var response = that.getIframeContentJSON(iframe);
- if (jQuery.isEmptyObject(that.modal)) {
- that.afterUpload(response);
- }
- }
- if (iframe.addEventListener)
- iframe.addEventListener("load", eventHandlermyFile, true);
- if (iframe.attachEvent)
- iframe.attachEvent("onload", eventHandlermyFile);
- return "#" + that.id + '_imgUploadField';
- } else {
- return "";
- }
- },
- SubmitFallbackIframe: function (that) {
- that.showLoader();
- if (that.options.processInline && !that.options.uploadUrl) {
- if (that.options.onError) {
- that.options.onError.call(that, "processInline is not supported by your browser ");
- that.hideLoader();
- }
- } else {
- if (that.options.onBeforeImgUpload) that.options.onBeforeImgUpload.call(that);
- that.iframeform[0].submit();
- }
- },
- getIframeContentJSON: function (iframe) {
- try {
- var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document,
- response;
- var innerHTML = doc.body.innerHTML;
- if (innerHTML.slice(0, 5).toLowerCase() == "<pre>" && innerHTML.slice(-6).toLowerCase() == "</pre>") {
- innerHTML = doc.body.firstChild.firstChild.nodeValue;
- }
- response = jQuery.parseJSON(innerHTML);
- } catch (err) {
- response = {success: false};
- }
- return response;
- },
- hexadecimal: function (num) {
- var r = parseInt(num).toString(16);
- if (r.length == 1) {
- return '0' + r;
- }
- return r.toUpperCase();
- }
- };
- })(window, document);
|