溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

通過HTML5移動開發(fā)實(shí)現(xiàn)圖片壓縮上傳的功能

發(fā)布時間:2020-07-10 10:32:09 來源:億速云 閱讀:148 作者:Leah 欄目:web開發(fā)

通過HTML5移動開發(fā)實(shí)現(xiàn)圖片壓縮上傳的功能?相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

移動端上傳圖片,用戶一般都是上傳手機(jī)相冊中的圖片,而現(xiàn)在手機(jī)的拍攝質(zhì)量越來越高,一般單張照片的尺寸都在3M左右,因此需要在上傳之前,先進(jìn)行本地壓縮。

H5活動已十分普遍,其中一種形式是讓用戶上傳圖片進(jìn)行參與。移動端上傳圖片,用戶一般都是上傳手機(jī)相冊中的圖片,而現(xiàn)在手機(jī)的拍攝質(zhì)量越來越高,一般單張照片的尺寸都在3M左右。若直接上傳,十分耗流量,并且體驗(yàn)效果也不佳。因此需要在上傳之前,先進(jìn)行本地壓縮。

接下來總結(jié)在h6活動的開發(fā)中圖片壓縮上傳的功能,并標(biāo)記其中踩過的幾個坑,分享給大家:

小白區(qū)必看

對于移動端圖片上傳毫無概念的話,需要補(bǔ)充FileReader、Blob、FormData三個概念。

1.FileReader

定義

使用FileReader對象,web應(yīng)用程序可以異步的讀取存儲在用戶計算機(jī)上的文件(或者原始數(shù)據(jù)緩沖)內(nèi)容,可以使用File對象或者Blob對象來指定所要處理的文件或數(shù)據(jù).

方法

通過HTML5移動開發(fā)實(shí)現(xiàn)圖片壓縮上傳的功能

事件處理程序

通過HTML5移動開發(fā)實(shí)現(xiàn)圖片壓縮上傳的功能

使用

var fileReader = new FileReader();
fileReader.onload = function() {
    var url = this.result;
}
//or
fileReader.onload = function(e) {
    var url = e.target.result;
}

2.Blob

BLOB(binary large object),二進(jìn)制大對象,是一個可以存儲二進(jìn)制文件的容器。

3.FormData

利用FormData對象,你可以使用一系列的鍵值對來模擬一個完整的表單,然后使用XMLHttpRequest發(fā)送這個”表單”.

正題

移動端圖片壓縮上傳過程:

1)input file上傳圖片,使用FileReader讀取用戶上傳的圖片;

2)圖片數(shù)據(jù)傳入img對象,將img繪制到canvas上,再使用canvas.toDataURL進(jìn)行壓縮;

3)獲取壓縮后的base64格式圖片數(shù)據(jù),轉(zhuǎn)成二進(jìn)制,塞入formdata,最后通過xmlHttpRequest提交formdata;

1.獲取圖片數(shù)據(jù)

fileEle.onchange = function() {
    if (!this.files.length) return;
    //以下考慮的是單圖情況
    var _ua = window.navigator.userAgent;
    var _simpleFile = this.files[0];
    //判斷是否為圖片
    if (!/\/(?:jpeg|png|gif)/i.test(_simpleFile.type)) return;
    //插件exif.js獲取ios圖片的方向信息
    var _orientation;
    if(_ua.indexOf('iphone') > 0) {
        EXIF.getData(_simpleFile,function(){
            _orientation=EXIF.getTag(this,'Orientation');
        });
    }
    //1.讀取文件,通過FileReader,將圖片文件轉(zhuǎn)化為DataURL,即data:img/png;base64,開頭的url,可以直接放在image.src中;
    var _reader = new FileReader(),
        _img = new Image(),
        _url;
    _reader.onload = function() {
        _url = this.result;
        _img.url = _url;
        _img.onload = function () {
            var _data = compress(_img);
            uploadPhoto(_data, _orientation);
        };
    };
    _reader.readAsDataURL(_simpleFile);
};

2.壓縮圖片

/**
 * 計算圖片的尺寸,根據(jù)尺寸壓縮
 * 1. iphone手機(jī)html5上傳圖片方向問題,借助exif.js
 * 2. 安卓UC瀏覽器不支持 new Blob(),使用BlobBuilder
 * @param  {Object} _img         圖片
 * @param  {Number} _orientation 照片信息
 * @return {String}              壓縮后base64格式的圖片
 */
function compress(_img, _orientation) {
    //2.計算符合目標(biāo)尺寸寬高值,若上傳圖片的寬高都大于目標(biāo)圖,對目標(biāo)圖等比壓縮;如果有一邊小于,對上傳圖片等比放大。
    var _goalWidth = 750,                  //目標(biāo)寬度
        _goalHeight = 750,                 //目標(biāo)高度
        _imgWidth = _img.naturalWidth,     //圖片寬度
        _imgHeight = _img.naturalHeight,   //圖片高度
        _tempWidth = _imgWidth,            //放大或縮小后的臨時寬度
        _tempHeight = _imgHeight,          //放大或縮小后的臨時寬度
        _r = 0;                            //壓縮比
    if(_imgWidth === _goalWidth && _imgHeight === _goalHeight) {
    } else if(_imgWidth > _goalWidth && _imgHeight > _goalHeight) {//寬高都大于目標(biāo)圖,需等比壓縮
        _r = _imgWidth / _goalWidth;
        if(_imgHeight / _goalHeight < _r) {
            _r = _imgHeight / _goalHeight;
        }
        _tempWidth = Math.ceil(_imgWidth / _r);
        _tempHeight = Math.ceil(_imgHeight / _r);
    } else {
        if(_imgWidth < _goalWidth && _imgHeight < _goalHeight) {//寬高都小于
            _r = _goalWidth / _imgWidth;
            if(_goalHeight / _imgHeight < _r) {
                _r = _goalHeight / _imgHeight;
            }
        } else {
            if(_imgWidth < _goalWidth) {         //寬小于
                _r = _goalWidth / _imgWidth;
            } else{                              //高小于
                _r = _goalHeight / _imgHeight;
            }
        }
        _tempWidth = Math.ceil(_imgWidth * _r);
        _tempHeight = Math.ceil(_imgHeight * _r);
    }
    //3.利用canvas對圖片進(jìn)行裁剪,等比放大或縮小后進(jìn)行居中裁剪
    var _canvas = e._$get('canvas-clip');
    if(!_canvas.getContext) return;
    var _context = _canvas.getContext('2d');
    _canvas.width = _tempWidth;
    _canvas.height = _tempHeight;
    var _degree;
    //ios bug,iphone手機(jī)上可能會遇到圖片方向錯誤問題
    switch(_orientation){
       //iphone橫屏拍攝,此時home鍵在左側(cè)
        case 3:
            _degree=180;
            _tempWidth=-_imgWidth;
            _tempHeight=-_imgHeight;
            break;
        //iphone豎屏拍攝,此時home鍵在下方(正常拿手機(jī)的方向)
        case 6:
            _canvas.width=_imgHeight;
            _canvas.height=_imgWidth; 
            _degree=90;
            _tempWidth=_imgWidth;
            _tempHeight=-_imgHeight;
            break;
        //iphone豎屏拍攝,此時home鍵在上方
        case 8:
            _canvas.width=_imgHeight;
            _canvas.height=_imgWidth; 
            _degree=270;
            _tempWidth=-_imgWidth;
            _tempHeight=_imgHeight;
            break;
    }
    if(window.navigator.userAgent.indexOf('iphone') > 0 && !!_degree) {
        _context.rotate(_degree*Math.PI/180);
        _context.drawImage(_img, 0, 0, _tempWidth, _tempHeight); 
    } else {
        _context.drawImage(_img, 0, 0, _tempWidth, _tempHeight);
    }
    //toDataURL方法,可以獲取格式為"data:image/png;base64,***"的base64圖片信息;
    var _data = _canvas.toDataURL('image/jpeg');
    return _data;
}

3.上傳圖片

/**
 * 上傳圖片到NOS
 * @param  {Object} _blog Blob格式的圖片
 * @return {Void}
 */
function uploadPhoto(_data) {
    //4.獲取canvas中的圖片信息
    //window.atob方法將其中的base64格式的圖片轉(zhuǎn)換成二進(jìn)制字符串;若將轉(zhuǎn)換后的值直接賦值給Blob會報錯,需Uint8Array轉(zhuǎn)換:最后創(chuàng)建Blob對象;
    _data = _data.split(',')[1];
    _data = window.atob(_data);
    //如果不用ArrayBuffer,發(fā)送給服務(wù)器的圖片格式是[object Uint8Array],上傳失敗...
    var _buffer = new ArrayBuffer(_data.length);
    var _ubuffer = new Uint8Array(_buffer);
    for (var i = 0; i < _data.length; i++) {
        _ubuffer[i] = _data.charCodeAt(i);
    }
    // 安卓 UC瀏覽器不支持 new Blob(),使用BlobBuilder
    var _blob;
    try {
        _blob = new Blob([_buffer], {type:'image/jpeg'});
    } catch(ee) {
        window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
        if (ee.name == 'TypeError' && window.BlobBuilder) {
            var _bb = new BlobBuilder();
            _bb.append(_buffer);
            _blob = _bb.getBlob('image/jpeg');
        }
    }
    var _suffix = 'jpg';
    if(_blob.type === 'image/jpeg') {
        _suffix = 'jpg';
    }
    //獲取NOStoken
    this.__cache._$requestDWRByGet({url: 'ImageBean.genTokens',param: [_suffix,'','','','1'],onload: function(_tokens) {
        _tokens = _tokens || [];
        var _token = _tokens[0];
        if(!_token || !_token.objectName || !_token.uploadToken){
            alert('token獲取失敗!');
            return false;
        }
        //上傳圖片到NOS
        var _objectName = _token.objectName,
            _uploadToken = _token.uploadToken,
            _bucketName = _token.bucketName;
        var _formData = new FormData();
        _formData.append('Object', _objectName);
        _formData.append('x-nos-token', _uploadToken);
        _formData.append('file',_blob);
        var _xhr;
        if (window.XMLHttpRequest) {
            _xhr = new window.XMLHttpRequest();
        } else if (window.ActiveXObject) {
            _xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        _xhr.onreadystatechange = function() {
            if(_xhr.readyState === 4) {
                if((_xhr.status >= 200 && _xhr.status < 300) || _xhr.status === 304) {
                    var _imgurl = "http://nos.netease.com/" + _bucketName + "/" + _objectName + "?imageView";
                    var _newUrl = mb.x._$imgResize(_imgurl, 750, 750, 1, true);
                    window.location.href = 'http://www.lofter.com/act/taxiu?op=effect&originImgUrl=' + _newUrl;
                }
            }
        };
        _xhr.open('POST', 'http://nos.netease.com/' + _bucketName, true);
        _xhr.send(_formData);
    }});
}

判斷iphone拍攝圖片方向的插件:exif

看完上述內(nèi)容,你們掌握通過HTML5移動開發(fā)實(shí)現(xiàn)圖片壓縮上傳的功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI