H5活動已十分普遍,其中一種形式是讓用戶上傳圖片參與。行動端上傳圖片,用戶一般都是上傳手機相簿中的圖片,而現在手機的拍攝品質越來越高,一般單張照片的尺寸都在3M左右。若直接上傳,十分耗流量,且體驗效果也不佳。因此需要在上傳之前,先進行本地壓縮。
接下來總結在h5活動的開發中圖片壓縮上傳的功能,並標記其中踩過的幾個坑,分享給大家:
小白區必看
對於移動端圖片上傳毫無概念的話,需要補充FileReader、Blob、FormData三個概念。
1.FileReader
定義
使用FileReader物件,web應用程式可以非同步的讀取儲存在使用者電腦上的檔案(或原始資料緩衝)內容,可以使用File物件或Blob物件來指定所要處理的檔案或資料.
方法
事件處理程序
使用
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),二進位儲存大物件,是一個可以進位的物件。
3.FormData
利用FormData物件,你可以使用一系列的鍵值對來模擬一個完整的表單,然後使用XMLHttpRequest發送這個」表單」.
正題
移動端圖片
1)input file上傳圖片,使用FileReader讀取用戶上傳的圖片;
2)圖片資料傳入img對象,將img繪製到canvas上,再使用canvas.toDataURL進行壓縮;
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,将图片文件转化为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.壓縮圖片
/** * 计算图片的尺寸,根据尺寸压缩 * 1. iphone手机html5上传图片方向问题,借助exif.js * 2. 安卓UC浏览器不支持 new Blob(),使用BlobBuilder * @param {Object} _img 图片 * @param {Number} _orientation 照片信息 * @return {String} 压缩后base64格式的图片 */ function compress(_img, _orientation) { //2.计算符合目标尺寸宽高值,若上传图片的宽高都大于目标图,对目标图等比压缩;如果有一边小于,对上传图片等比放大。 var _goalWidth = 750, //目标宽度 _goalHeight = 750, //目标高度 _imgWidth = _img.naturalWidth, //图片宽度 _imgHeight = _img.naturalHeight, //图片高度 _tempWidth = _imgWidth, //放大或缩小后的临时宽度 _tempHeight = _imgHeight, //放大或缩小后的临时宽度 _r = 0; //压缩比 if(_imgWidth === _goalWidth && _imgHeight === _goalHeight) { } else if(_imgWidth > _goalWidth && _imgHeight > _goalHeight) {//宽高都大于目标图,需等比压缩 _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对图片进行裁剪,等比放大或缩小后进行居中裁剪 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手机上可能会遇到图片方向错误问题 switch(_orientation){ //iphone横屏拍摄,此时home键在左侧 case 3: _degree=180; _tempWidth=-_imgWidth; _tempHeight=-_imgHeight; break; //iphone竖屏拍摄,此时home键在下方(正常拿手机的方向) 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格式的图片转换成二进制字符串;若将转换后的值直接赋值给Blob会报错,需Uint8Array转换:最后创建Blob对象; _data = _data.split(',')[1]; _data = window.atob(_data); //如果不用ArrayBuffer,发送给服务器的图片格式是[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); }}); }exif至此H5圖片壓縮上傳的流程結束。

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5開發需要掌握的工具和框架包括Vue.js、React和Webpack。 1.Vue.js適用於構建用戶界面,支持組件化開發。 2.React通過虛擬DOM優化頁面渲染,適合複雜應用。 3.Webpack用於模塊打包,優化資源加載。

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5通過語義化元素和ARIA屬性提升網頁的可訪問性和SEO效果。 1.使用、、等元素組織內容結構,提高SEO。 2.ARIA屬性如aria-label增強可訪問性,輔助技術用戶可順利使用網頁。

"h5"和"HTML5"在大多數情況下是相同的,但它們在某些特定場景下可能有不同的含義。 1."HTML5"是W3C定義的標準,包含新標籤和API。 2."h5"通常是HTML5的簡稱,但在移動開發中可能指基於HTML5的框架。理解這些區別有助於在項目中準確使用這些術語。

H5,即HTML5,是HTML的第五個版本,它為開發者提供了更強大的工具集,使得創建複雜的網頁應用變得更加簡單。 H5的核心功能包括:1)元素允許在網頁上繪製圖形和動畫;2)語義化標籤如、等,使網頁結構清晰,利於SEO優化;3)新API如GeolocationAPI,支持基於位置的服務;4)跨瀏覽器兼容性需要通過兼容性測試和Polyfill庫來確保。

如何創建 H5 鏈接?確定鏈接目標:獲取 H5 頁面或應用程序的 URL。創建 HTML 錨點:使用 <a> 標記創建錨點並指定鏈接目標URL。設置鏈接屬性(可選):根據需要設置 target、title 和 onclick 屬性。添加到網頁:將 HTML 錨點代碼添加到希望鏈接出現的網頁中。

解決 H5 兼容問題的方法包括:使用響應式設計,允許網頁根據屏幕尺寸調整佈局。採用跨瀏覽器測試工具,在發布前測試兼容性。使用 Polyfill,為舊瀏覽器提供對新 API 的支持。遵循 Web 標準,使用有效的代碼和最佳實踐。使用 CSS 預處理器,簡化 CSS 代碼並提高可讀性。優化圖像,減小網頁大小並加快加載速度。啟用 HTTPS,確保網站的安全性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

WebStorm Mac版
好用的JavaScript開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境