我們都知道在“寸土寸金”的互聯(lián)網(wǎng)時(shí)代, 速度是第一競(jìng)爭(zhēng)力, 雖然我們的5G發(fā)展已經(jīng)搖搖領(lǐng)先, 但是也經(jīng)不住用戶在一個(gè)網(wǎng)頁(yè)里傳很多“巨無(wú)霸”圖片, 最終導(dǎo)致的結(jié)果就是頁(yè)面“龜速”打開......
圖片
那么作為技術(shù)人, 當(dāng)然也有一堆的解決方案, 比如:
當(dāng)然聰明的小伙伴也會(huì)將上面的方案組合, 設(shè)計(jì)更優(yōu)秀的圖片“提速”方案.
今天不會(huì)和大家把所有方案都介紹一遍, 因?yàn)榫W(wǎng)上也有很多實(shí)踐, 接下來會(huì)從前端技術(shù)提升的角度, 分享一下如何用原生 javascript, 實(shí)現(xiàn)從圖片上傳到圖片自定義壓縮的完整方案. 大家可以把文章中介紹的方案直接用于自己的實(shí)際開發(fā)中, 或者基于它設(shè)計(jì)更棒的圖片壓縮方案.
圖片
前端實(shí)現(xiàn)圖片壓縮無(wú)非就是在用戶上傳圖片文件后, 將file轉(zhuǎn)換成image對(duì)象, 然后再利用canvas 及其 api 將圖片壓縮成指定體積. 如下流程:
圖片
首先我們先實(shí)現(xiàn)將file轉(zhuǎn)換成image對(duì)象, 這里我們用到了FileReader API, 代碼如下:
// 壓縮前將file轉(zhuǎn)換成img對(duì)象function readImg(file:File) { return new Promise((resolve, reject) => { const img = new Image() const reader = new FileReader() reader.onload = function(e:any) { img.src = e.target.result } reader.onerror = function(e) { reject(e) } reader.readAsDataURL(file) img.onload = function() { resolve(img) } img.onerror = function(e) { reject(e) } })}
這里使用 promise 來設(shè)計(jì)生成圖片數(shù)據(jù)的方法, 接下來我們看看核心的圖片壓縮源碼:
/** * 壓縮圖片 * @param img 被壓縮的img對(duì)象 * @param type 壓縮后轉(zhuǎn)換的文件類型 * @param mx 觸發(fā)壓縮的圖片最大寬度限制 * @param mh 觸發(fā)壓縮的圖片最大高度限制 * @param quality 圖片質(zhì)量 */ function compressImg(img: any, type:string, mx: number, mh: number, quality:number = 1) { return new Promise((resolve, reject) => { const canvas = document.createElement('canvas') const context = canvas.getContext('2d') const { width: originWidth, height: originHeight } = img // 最大尺寸限制 const maxWidth = mx const maxHeight = mh // 目標(biāo)尺寸 let targetWidth = originWidth let targetHeight = originHeight if (originWidth > maxWidth || originHeight > maxHeight) { if (originWidth / originHeight > 1) { // 寬圖片 targetWidth = maxWidth targetHeight = Math.round(maxWidth * (originHeight / originWidth)) } else { // 高圖片 targetHeight = maxHeight targetWidth = Math.round(maxHeight * (originWidth / originHeight)) } } canvas.width = targetWidth canvas.height = targetHeight context?.clearRect(0, 0, targetWidth, targetHeight) // 圖片繪制 context?.drawImage(img, 0, 0, targetWidth, targetHeight) canvas.toBlob(function(blob) { resolve(blob) }, type || 'image/png', quality) })}
這里通過控制 canvas的寬高, 以及對(duì) canvas 的 toBlob設(shè)置參數(shù), 來實(shí)現(xiàn)自定義的圖片壓縮.
如果大家對(duì)代碼又不理解的地方, 也可以在文末發(fā)表問題, 我會(huì)做對(duì)應(yīng)的解答.
本文鏈接:http://www.www897cc.com/showinfo-26-16935-0.html開箱即用的前端圖片壓縮方案
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com