亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

WEB前端實現(xiàn)裁剪上傳圖片功能

 更新時間:2016年10月17日 11:08:07   作者:會編程的銀豬  
文件上傳功能在各大網(wǎng)站經(jīng)常會用到,今天小編通過本文給大家介紹了WEB前端實現(xiàn)裁剪上傳圖片功能的相關(guān)資料,需要的朋友可以參考下

最后的效果如下:

這里面有幾個功能,第一個是支持拖拽,第二個壓縮,第三個是裁剪編輯,第四個是上傳和上傳進(jìn)度顯示,下面依次介紹每個功能的實現(xiàn):

1. 拖拽顯示圖片

拖拽讀取的功能主要是要兼聽html5的drag事件,這個沒什么好說的,查查api就知道怎么做了,主要在于怎么讀取用戶拖過來的圖片并把它轉(zhuǎn)成base64以在本地顯示。

var handler = {
init: function($container){
//需要把dragover的默認(rèn)行為禁掉,不然會跳頁
$container.on("dragover", function(event){
event.preventDefault();
});
$container.on("drop", function(event){
event.preventDefault();
//這里獲取拖過來的圖片文件,為一個File對象
var file = event.originalEvent.dataTransfer.files[0];
handler.handleDrop($(this), file);
});
}
}
varhandler={
init:function($container){
//需要把dragover的默認(rèn)行為禁掉,不然會跳頁
$container.on("dragover",function(event){
event.preventDefault();
});
$container.on("drop",function(event){
event.preventDefault();
//這里獲取拖過來的圖片文件,為一個File對象
varfile=event.originalEvent.dataTransfer.files[0];
handler.handleDrop($(this),file);
});
}
}

代碼第10行獲取圖片文件,然后傳給11行處理。

如果使用input,則監(jiān)聽input的change事件:

$container.on("change", "input[type=file]", function(event){
if(!this.value) return;
var file = this.files[0];
handler.handleDrop($(this).closest(".container"), file);
this.value = "";
});
$container.on("change","input[type=file]",function(event){
if(!this.value)return;
varfile=this.files[0];
handler.handleDrop($(this).closest(".container"),file);
this.value="";
});

代碼第3行,獲取File對象,同樣傳給handleDrop進(jìn)行處理

接下來在handleDrop函數(shù)里,讀取file的內(nèi)容,并把它轉(zhuǎn)成base64的格式:

handleDrop: function($container, file){
var $img = $container.find("img");
handler.readImgFile(file, $img, $container);
},
handleDrop:function($container,file){
var$img= $container.find("img");
handler.readImgFile(file,$img,$container);
},

我的代碼里面又調(diào)了個readImgFile的函數(shù),helper的函數(shù)比較多,主要是為了拆解大模塊和復(fù)用小模塊。

在readImgFile里面讀取圖片文件內(nèi)容:

使用FileReader讀取文件 JavaScript

readImgFile: function(file, $img, $container){
var reader = new FileReader(file);
//檢驗用戶是否選則是圖片文件
if(file.type.split("/")[0] !== "image"){
util.toast("You should choose an image file");
return;
} 
reader.onload = function(event) {
var base64 = event.target.result;
handler.compressAndUpload($img, base64, file, $container);
} 
reader.readAsDataURL(file);
}
readImgFile:function(file,$img,$container){
varreader=newFileReader(file);
//檢驗用戶是否選則是圖片文件
if(file.type.split("/")[0]!=="image"){
util.toast("You should choose an image file");
return;
} 
reader.onload=function(event){
varbase64=event.target.result;
handler.compressAndUpload($img,base64,file, $container);
} 
reader.readAsDataURL(file);
}

這里是通過FileReader讀取文件內(nèi)容,調(diào)的是readAsDataURL,這個api能夠把二進(jìn)制圖片內(nèi)容轉(zhuǎn)成base64的格式,讀取完之后會觸發(fā)onload事件,在onload里面進(jìn)行顯示和上傳:

//獲取圖片base64內(nèi)容
var base64 = event.target.result;
//如果圖片大于1MB,將body置半透明
if(file.size > ONE_MB){
$("body").css("opacity", 0.5);
}
//因為這里圖片太大會被卡一下,整個頁面會不可操作
$img.attr("src", baseUrl);
//還原
if(file.size > ONE_MB){
$("body").css("opacity", 1);
}
//然后再調(diào)一個壓縮和上傳的函數(shù)
handler.compressAndUpload($img, file, $container);
//獲取圖片base64內(nèi)容
varbase64=event.target.result;
//如果圖片大于1MB,將body置半透明
if(file.size>ONE_MB){
$("body").css("opacity",0.5);
}
//因為這里圖片太大會被卡一下,整個頁面會不可操作
$img.attr("src",baseUrl);
//還原
if(file.size>ONE_MB){
$("body").css("opacity",1);
}
//然后再調(diào)一個壓縮和上傳的函數(shù)
handler.compressAndUpload($img,file,$container);

如果圖片有幾個Mb的,在上面第8行展示的時候被卡一下,筆者曾嘗試使用web worker多線程解決,但是由于多線程沒有window對象,更不能操作dom,所以不能很好地解決這個問題。采取了一個補(bǔ)償措施:通過把頁面變虛告訴用戶現(xiàn)在在處理之中,頁面不可操作,稍等一會

這里還會有一個問題,就是ios系統(tǒng)拍攝的照片,如果不是橫著拍的,展示出來的照片旋轉(zhuǎn)角度會有問題,如下一張豎著拍的照片,讀出來是這樣的:


即不管你怎么拍,ios實際存的圖片都是橫著放的,因此需要用戶自己手動去旋轉(zhuǎn)。旋轉(zhuǎn)的角度放在了exif的數(shù)據(jù)結(jié)構(gòu)里面,把這個讀出來就知道它的旋轉(zhuǎn)角度了,用一個EXIF的庫讀?。?/p>

讀取exif的信息

readImgFile: function(file, $img, $container){
EXIF.getData(file, function(){
var orientation = this.exifdata.Orientation,
rotateDeg = 0;
//如果不是ios拍的照片或者是橫拍的,則不用處理,直接讀取
if(typeof orientation === "undefined" || orientation === 1){ 
//原本的readImgFile,添加一個rotateDeg的參數(shù)
handler.doReadImgFile(file, $img, $container, rotateDeg);
} 
//否則用canvas旋轉(zhuǎn)一下
else{
rotateDeg = orientation === 6 ? 90*Math.PI/180 : 
orientation === 8 ? -90*Math.PI/180 :
orientation === 3 ? 180*Math.PI/180 : 0;
handler.doReadImgFile(file, $img, $container, rotateDeg);
} 
});
}

readImgFile:function(file,$img,$container){
EXIF.getData(file,function(){
varorientation=this.exifdata.Orientation,
rotateDeg=0;
//如果不是ios拍的照片或者是橫拍的,則不用處理,直接讀取
if(typeoforientation==="undefined"||orientation===1){
//原本的readImgFile,添加一個rotateDeg的參數(shù)
handler.doReadImgFile(file,$img,$container,rotateDeg);
} 
//否則用canvas旋轉(zhuǎn)一下
else{
rotateDeg=orientation===6?90*Math.PI/180:
orientation===8?-90*Math.PI/180:
orientation===3?180*Math.PI/180:0;
handler.doReadImgFile(file,$img,$container,rotateDeg);
} 
});
}

知道角度之后,就可以用canvas處理了,在下面的壓縮圖片進(jìn)行說明,因為壓縮也要用到canvas

2. 壓縮圖片

壓縮圖片可以借助canvas,canvas可以很方便地實現(xiàn)壓縮,其原理是把一張圖片畫到一個小的畫布,然后再把這個畫布的內(nèi)容導(dǎo)出base64,就能夠拿到一張被壓小的圖片了:

//設(shè)定圖片最大壓縮寬度為1500px
var maxWidth = 1500;
var resultImg = handler.compress($img[0], maxWidth, file.type);
//設(shè)定圖片最大壓縮寬度為1500px
varmaxWidth=1500;
varresultImg=handler.compress($img[0],maxWidth,file.type);

compress函數(shù)進(jìn)行壓縮,在這個函數(shù)里首先創(chuàng)建一個canvas對象,然后計算這個畫布的大?。?/p>

compress: function(img, maxWidth, mimeType){
//創(chuàng)建一個canvas對象
var cvs = document.createElement('canvas');
var width = img.naturalWidth,
height = img.naturalHeight,
imgRatio = width / height;
//如果圖片維度超過了給定的maxWidth 1500,
//為了保持圖片寬高比,計算畫布的大小
if(width > maxWidth){
width = maxWidth;
height = width / imgRatio;
} 
cvs.width = width;
cvs.height = height;
}
compress:function(img,maxWidth,mimeType){
//創(chuàng)建一個canvas對象
varcvs=document.createElement('canvas');
varwidth=img.naturalWidth,
height=img.naturalHeight,
imgRatio=width/height;
//如果圖片維度超過了給定的maxWidth 1500,
//為了保持圖片寬高比,計算畫布的大小
if(width>maxWidth){
width=maxWidth;
height=width/imgRatio;
} 
cvs.width=width;
cvs.height=height;
}

接下來把大的圖片畫到一個小的畫布上,再導(dǎo)出:

//把大圖片畫到一個小畫布
var ctx = cvs.getContext("2d").drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, width, height);
//圖片質(zhì)量進(jìn)行適當(dāng)壓縮
var quality = width >= 1500 ? 0.5 :
width > 600 ? 0.6 : 1;
//導(dǎo)出圖片為base64
var newImageData = cvs.toDataURL(mimeType, quality);
var resultImg = new Image();
resultImg.src = newImageData;
return resultImg;
//把大圖片畫到一個小畫布
varctx=cvs.getContext("2d").drawImage(img,0,0,img.naturalWidth,img.naturalHeight,0,0,width,height);
//圖片質(zhì)量進(jìn)行適當(dāng)壓縮
varquality=width>=1500?0.5:
width>600?0.6:1;
//導(dǎo)出圖片為base64
varnewImageData=cvs.toDataURL(mimeType,quality);
varresultImg=newImage();
resultImg.src=newImageData;
returnresultImg;

最后一行返回了一個被壓縮過的小圖片,就可對這個圖片進(jìn)行裁剪了。

在說明裁剪之前,由于第二點(diǎn)提到ios拍的照片需要旋轉(zhuǎn)一下,在壓縮的時候可以一起處理。也就是說,如果需要旋轉(zhuǎn)的話,那么畫在canvas上面就把它旋轉(zhuǎn)好了:

var ctx = cvs.getContext("2d");
var destX = 0,
destY = 0;
if(rotateDeg){
ctx.translate(cvs.width / 2, cvs.height / 2);
ctx.rotate(rotateDeg);
destX = -width / 2,
destY = -height / 2;
}
ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, destX, destY, width, height);
varctx=cvs.getContext("2d");
vardestX=0,
destY=0;
if(rotateDeg){
ctx.translate(cvs.width/2,cvs.height/2);
ctx.rotate(rotateDeg);
destX=-width/2,
destY=-height/2;
}
ctx.drawImage(img,0,0,img.naturalWidth,img.naturalHeight,destX,destY,width,height);

這樣就解決了ios圖片旋轉(zhuǎn)的問題,得到一張旋轉(zhuǎn)和壓縮調(diào)節(jié)過的圖片之后,再用它進(jìn)行裁剪和編輯

3. 裁剪圖片

裁剪圖片,上網(wǎng)找到了一個插件cropper,這個插件還是挺強(qiáng)大,支持裁剪、旋轉(zhuǎn)、翻轉(zhuǎn),但是它并沒有對圖片真正的處理,只是記錄了用戶做了哪些變換,然后你自己再去處理??梢园炎儞Q的數(shù)據(jù)傳給后端,讓后端去處理。這里我們在前端處理,因為我們不用去兼容IE8。

如下,我把一張圖片,旋轉(zhuǎn)了一下,同時翻轉(zhuǎn)了一下:

它的輸出是:

{
height: 319.2000000000001,
rotate: 45,
scaleX: -1,
scaleY: 1,
width: 319.2000000000001
x: 193.2462838120872
y: 193.2462838120872
}
{
height:319.2000000000001,
rotate:45,
scaleX:-1,
scaleY:1,
width:319.2000000000001
x:193.2462838120872
y:193.2462838120872
}

通過這些信息就知道了:圖片被左右翻轉(zhuǎn)了一下,同時順時針轉(zhuǎn)了45度,還知道裁剪選框的位置和大小。通過這些完整的信息就可以做一對一的處理。

在展示的時候,插件使用的是img標(biāo)簽,設(shè)置它的css的transform屬性進(jìn)行變換。真正的處理還是要借助canvas,這里分三步說明:

1. 假設(shè)用戶沒有進(jìn)行旋轉(zhuǎn)和翻轉(zhuǎn),只是選了簡單地選了下區(qū)域裁剪了一下,那就簡單很多。最簡單的辦法就是創(chuàng)建一個canvas,它的大小就是選框的大小,然后根據(jù)起點(diǎn)x、y和寬高把圖片相應(yīng)的位置畫到這個畫布,再導(dǎo)出圖片就可以了。由于考慮到需要翻轉(zhuǎn),所以用第二種方法,創(chuàng)建一個和圖片一樣大小的canvas,把圖片原封不動地畫上去,然后把選中區(qū)域的數(shù)據(jù)imageData存起來,重新設(shè)置畫布的大小為選中框的大小,再把imageData畫上去,最后再導(dǎo)出就可以了:

var cvs = document.createElement('canvas');
var img = $img[0];
var width = img.naturalWidth,
height = img.naturalHeight;
cvs.width = width;
cvs.height = height; 
var ctx = cvs.getContext("2d");
var destX = 0,
destY = 0;
ctx.drawImage(img, destX, destY);
//把選中框里的圖片內(nèi)容存起來
var imageData = ctx.getImageData(cropOptions.x, cropOptions.y, cropOptions.width, cropOptions.height);
cvs.width = cropOptions.width;
cvs.height = cropOptions.height;
//然后再畫上去
ctx.putImageData(imageData, 0, 0);
varcvs=document.createElement('canvas');
varimg=$img[0];
varwidth=img.naturalWidth,
height=img.naturalHeight;
cvs.width=width;
cvs.height=height;
varctx=cvs.getContext("2d");
vardestX=0,
destY=0;
ctx.drawImage(img,destX,destY);
//把選中框里的圖片內(nèi)容存起來
varimageData=ctx.getImageData(cropOptions.x,cropOptions.y,cropOptions.width,cropOptions.height);
cvs.width=cropOptions.width;
cvs.height=cropOptions.height;
//然后再畫上去
ctx.putImageData(imageData,0,0);

代碼14行,通過插件給的數(shù)據(jù),保存選中區(qū)域的圖片數(shù)據(jù),18行再把它畫上去

2. 如果用戶做了翻轉(zhuǎn),用上面的結(jié)構(gòu)很容易可以實現(xiàn),只需要在第11行drawImage之前對畫布做一下翻轉(zhuǎn)變化:

canvas flip實現(xiàn) JavaScript

//fip
if(cropOptions.scaleX === -1 || cropOptions.scaleY === -1){
destX = cropOptions.scaleX === -1 ? width * -1 : 0; // Set x position to -100% if flip horizontal
destY = cropOptions.scaleY === -1 ? height * -1 : 0; // Set y position to -100% if flip vertical
ctx.scale(cropOptions.scaleX, cropOptions.scaleY);
}

ctx.drawImage(img, destX, destY);

//fip
if(cropOptions.scaleX===-1||cropOptions.scaleY===-1){
destX=cropOptions.scaleX===-1?width*-1:0; // Set x position to -100% if flip horizontal
destY=cropOptions.scaleY===-1?height*-1:0; // Set y position to -100% if flip vertical
ctx.scale(cropOptions.scaleX,cropOptions.scaleY);
}

ctx.drawImage(img,destX,destY);

其它的都不用變,就可以實現(xiàn)上下左右翻轉(zhuǎn)了,難點(diǎn)在于既要翻轉(zhuǎn)又要旋轉(zhuǎn)

3. 兩種變換疊加沒辦法直接通過變化canvas的坐標(biāo),一次性drawImage上去。還是有兩種辦法,第一種是用imageData進(jìn)行數(shù)學(xué)變換,計算一遍得到imageData里面,從第一行到最后一行每個像素新的rgba值是多少,然后再畫上去;第二種辦法,就是創(chuàng)建第二個canvas,第一個canvas作翻轉(zhuǎn),把它的結(jié)果畫到第二個canvas,然后再旋轉(zhuǎn),最后導(dǎo)到。由于第二種辦法相對比較簡單,我們采取第二種辦法:

同上,在第一個canvas畫完之后:

實現(xiàn)旋轉(zhuǎn)、翻轉(zhuǎn)結(jié)合 JavaScript

ctx.drawImage(img, destX, destY);
//rotate
if(cropOptions.rotate !== 0){
var newCanvas = document.createElement("canvas"),
deg = cropOptions.rotate / 180 * Math.PI;
//旋轉(zhuǎn)之后,導(dǎo)致畫布變大,需要計算一下
newCanvas.width = Math.abs(width * Math.cos(deg)) + Math.abs(height * Math.sin(deg));
newCanvas.height = Math.abs(width * Math.sin(deg)) + Math.abs(height * Math.cos(deg));
var newContext = newCanvas.getContext("2d");
newContext.save();
newContext.translate(newCanvas.width / 2, newCanvas.height / 2);
newContext.rotate(deg);
destX = -width / 2,
destY = -height / 2;
//將第一個canvas的內(nèi)容在經(jīng)旋轉(zhuǎn)后的坐標(biāo)系畫上來
newContext.drawImage(cvs, destX, destY);
newContext.restore();
ctx = newContext;
cvs = newCanvas;
}
ctx.drawImage(img,destX,destY);
//rotate
if(cropOptions.rotate!==0){
varnewCanvas=document.createElement("canvas"),
deg=cropOptions.rotate/180*Math.PI;
//旋轉(zhuǎn)之后,導(dǎo)致畫布變大,需要計算一下
newCanvas.width=Math.abs(width*Math.cos(deg))+Math.abs(height*Math.sin(deg));
newCanvas.height=Math.abs(width*Math.sin(deg))+Math.abs(height*Math.cos(deg));
varnewContext=newCanvas.getContext("2d");
newContext.save();
newContext.translate(newCanvas.width/2,newCanvas.height/2);
newContext.rotate(deg);
destX=-width/2,
destY=-height/2;
//將第一個canvas的內(nèi)容在經(jīng)旋轉(zhuǎn)后的坐標(biāo)系畫上來
newContext.drawImage(cvs,destX,destY);
newContext.restore();
ctx=newContext;
cvs=newCanvas;
}

將第二步的代碼插入第一步,再將第三步的代碼插入第二步,就是一個完整的處理過程了。

最后再介紹下上傳

4. 文件上傳和上傳進(jìn)度

文件上傳只能通過表單提交的形式,編碼方式為multipart/form-data,這個我在《三種上傳文件不刷新頁面的方法討論:iframe/FormData/FileReader》已做詳細(xì)討論,可以通過寫一個form標(biāo)簽進(jìn)行提交,但也可以模擬表單提交的格式,表單提交的格式在那篇文章已提及。

首先創(chuàng)建一個ajax請求:

JavaScript

var xhr = new XMLHttpRequest();
xhr.open('POST', upload_url, true);
var boundary = 'someboundary';
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
varxhr=newXMLHttpRequest();
xhr.open('POST',upload_url,true);
varboundary='someboundary';
xhr.setRequestHeader('Content-Type','multipart/form-data; boundary='+boundary);

并設(shè)置編碼方式,然后拼表單格式的數(shù)據(jù)進(jìn)行上傳:

ajax上傳 JavaScript

var data = img.src;
data = data.replace('data:' + file.type + ';base64,', '');
xhr.sendAsBinary([
//name=data
'--' + boundary,
'Content-Disposition: form-data; name="data"; filename="' + file.name + '"',
'Content-Type: ' + file.type, '',
atob(data), '--' + boundary,
//name=docName
'--' + boundary,
'Content-Disposition: form-data; name="docName"', '',
file.name,
'--' + boundary + '--'
].join('\r\n'));

vardata=img.src;
data=data.replace('data:'+file.type+';base64,','');
xhr.sendAsBinary([
//name=data
'--'+boundary,
'Content-Disposition: form-data; name="data"; filename="'+file.name+'"',
'Content-Type: '+file.type,'',
atob(data),'--'+boundary,
//name=docName
'--'+boundary,
'Content-Disposition: form-data; name="docName"','',
file.name,
'--'+boundary+'--'
].join('\r\n'));

表單數(shù)據(jù)不同的字段是用boundary的隨機(jī)字符串分隔的。拼好之后用sendAsBinary發(fā)出去,在調(diào)這個函數(shù)之前先監(jiān)聽下它的事件,包括

1) 上傳的進(jìn)度:

上傳進(jìn)度 JavaScript

xhr.upload.onprogress = function(event){
if(event.lengthComputable) {
duringCallback((event.loaded / event.total) * 100);
}
};
xhr.upload.onprogress=function(event){
if(event.lengthComputable){
duringCallback((event.loaded/event.total)*100);
}
};

這里凋duringCallback的回調(diào)函數(shù),給這個回調(diào)函數(shù)傳了當(dāng)前進(jìn)度的參數(shù),用這個參數(shù)就可以設(shè)置進(jìn)度條的過程了。進(jìn)度條可以自己實現(xiàn),或者直接上網(wǎng)找一個,隨便一搜就有了。

2) 成功和失敗:

成功和失敗回調(diào) JavaScript

xhr.onreadystatechange = function() {
if (this.readyState == 4){
if (this.status == 200) {
successCallback(this.responseText);
}else if (this.status >= 400) {
if (errorCallback && errorCallback instanceof Function) {
errorCallback(this.responseText);
} 
} 
}
};
xhr.onreadystatechange=function(){
if(this.readyState==4){
if(this.status==200){
successCallback(this.responseText);
}elseif(this.status>=400){
if(errorCallback&& errorCallback instanceofFunction){
errorCallback(this.responseText);
} 
} 
}
};

這個上傳功能參考了一個JIC插件

至此整個功能就拆解說明完了,上面的代碼可以兼容到IE10,F(xiàn)ileReader的api到IE10才兼容,問題應(yīng)該不大,因為微軟都已經(jīng)放棄了IE11以下的瀏覽器,為啥我們還要去兼容呢。

這個東西一來減少了后端的壓力,二來不用和后端來回交互,對用戶來說還是比較好的,除了上面說的一個地方會被卡一下之外。核心代碼已在上面說明,完整代碼和demo就不再放出來了。

以上所述是小編給大家介紹的WEB前端實現(xiàn)裁剪上傳圖片功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論