欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

如何使用HTML5移動開發(fā)圖片壓縮上傳功能

這篇文章主要為大家展示了“如何使用HTML5移動開發(fā)圖片壓縮上傳功能”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何使用HTML5移動開發(fā)圖片壓縮上傳功能”這篇文章吧。

成都創(chuàng)新互聯(lián)公司是一家網(wǎng)站建設(shè)、成都做網(wǎng)站,提供網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),網(wǎng)站制作,建網(wǎng)站,按需策劃,網(wǎng)站開發(fā)公司,從2013年成立是互聯(lián)行業(yè)建設(shè)者,服務(wù)者。以提升客戶品牌價(jià)值為核心業(yè)務(wù),全程參與項(xiàng)目的網(wǎng)站策劃設(shè)計(jì)制作,前端開發(fā),后臺程序制作以及后期項(xiàng)目運(yùn)營并提出專業(yè)建議和思路。

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

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

小白區(qū)必看

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

1.FileReader

定義

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

方法

如何使用HTML5移動開發(fā)圖片壓縮上傳功能

事件處理程序

如何使用HTML5移動開發(fā)圖片壓縮上傳功能

使用

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)制大對象,是一個(gè)可以存儲二進(jìn)制文件的容器。

3.FormData

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

正題

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

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ì)算圖片的尺寸,根據(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.計(jì)算符合目標(biāo)尺寸寬高值,若上傳圖片的寬高都大于目標(biāo)圖,對目標(biāo)圖等比壓縮;如果有一邊小于,對上傳圖片等比放大。
    var _goalWidth = 750,                  //目標(biāo)寬度
        _goalHeight = 750,                 //目標(biāo)高度
        _imgWidth = _img.naturalWidth,     //圖片寬度
        _imgHeight = _img.naturalHeight,   //圖片高度
        _tempWidth = _imgWidth,            //放大或縮小后的臨時(shí)寬度
        _tempHeight = _imgHeight,          //放大或縮小后的臨時(shí)寬度
        _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ī)上可能會遇到圖片方向錯(cuò)誤問題
    switch(_orientation){
       //iphone橫屏拍攝,此時(shí)home鍵在左側(cè)
        case 3:
            _degree=180;
            _tempWidth=-_imgWidth;
            _tempHeight=-_imgHeight;
            break;
        //iphone豎屏拍攝,此時(shí)home鍵在下方(正常拿手機(jī)的方向)
        case 6:
            _canvas.width=_imgHeight;
            _canvas.height=_imgWidth; 
            _degree=90;
            _tempWidth=_imgWidth;
            _tempHeight=-_imgHeight;
            break;
        //iphone豎屏拍攝,此時(shí)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會報(bào)錯(cuò),需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

以上是“如何使用HTML5移動開發(fā)圖片壓縮上傳功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

網(wǎng)站題目:如何使用HTML5移動開發(fā)圖片壓縮上傳功能
轉(zhuǎn)載源于:http://www.chinadenli.net/article14/jcocge.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號微信小程序域名注冊網(wǎng)站設(shè)計(jì)公司App設(shè)計(jì)Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化