項目中的一個基礎功能-----手機上傳圖片
技術棧:
1、利用canvas進行壓縮(這個應該都比較熟悉)
2、利用exif-js獲取照片旋轉角度屬性,因爲有些手機機型會因爲拍照時手機的方向使拍的照片帶一個旋轉角度的屬性
核心代碼:
var _orientation; //照片角度屬性
EXIF.getData(fileInput, function () {
_orientation = EXIF.getTag(fileInput, 'Orientation');
});
let reader = new FileReader();
reader.readAsDataURL(fileInput);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var canvas = document.createElement("canvas"); //創建臨時畫布
var _width = this.width, _height = this.height, _ratio = _height / _width;
//等比壓縮
if (this.width > 800) {
_width = 800;
_height = 800 * _ratio;
}
canvas.width = _width;
canvas.height = _height;
var ctx = canvas.getContext("2d");
switch (_orientation) {
case 6: // 旋轉90度
canvas.width = _height;
canvas.height = _width;
ctx.rotate(Math.PI / 2);
ctx.drawImage(this, 0, -_height, _width, _height);
break;
case 3: // 旋轉180度
ctx.rotate(Math.PI);
ctx.drawImage(this, -_width, -_height, _width, _height);
break;
case 8: // 旋轉-90度
canvas.width = _height;
canvas.height = _width;
ctx.rotate(3 * Math.PI / 2);
ctx.drawImage(this, -_width, 0, _width, _height);
break;
default:
ctx.drawImage(this, 0, 0, _width, _height);
}
//需要上傳的數據對象
const resultBase =dataURItoBlob(canvas.toDataURL("image/jpeg", 0.9));
//...省略進行上傳操作代碼
};
}
//將dataURI轉成Blob用於上傳
dataURItoBlob:function(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
你會經常地遇到 bug 和其它一些問題。這可能會讓人沮喪,但你要儘量保持冷靜,並系統地去思考。記住實踐是解決問題的最佳方法。
我們採集的是石頭,但是必須時刻展望未來的大教堂。
這裏推薦一下我的前端學習交流羣:784783012 ,裏面都是學習前端的,從最基礎的HTML+CSS+JS【炫酷特效,遊戲,插件封裝,設計模式】到移動端HTML5的項目實戰的學習資料都有整理,送給每一位前端小夥伴。最新技術,與企業需求同步,好友都在裏面學習交流,每天都會有大牛定時講解前端技術!
點擊:加入