JavaScrip實(shí)現(xiàn)圖片壓縮與分辨率等比例縮放
實(shí)現(xiàn)代碼
<input type="file" id="file" /> <script> function imageScale(width, originWidth, originHeight) { const scaleRatio = width / originWidth; const scaleHeight = scaleRatio * originHeight; return [width, scaleHeight]; } function compress(file, scaleWidth, quality = 0.5) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = (e) => { let img = new Image(); img.src = e.target.result; img.onload = function () { // 等比例縮放圖片 const [width, height] = imageScale( scaleWidth, img.width, img.height ); let canvas = document.createElement("canvas"); img.width = canvas.width = width; img.height = canvas.height = height; let ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); canvas.toBlob( (blob) => { resolve(blob); }, "image/jpeg", quality ); }; img.onerror = function () { reject(); }; }; }); } file.onchange = function () { compress(this.files[0], 200).then((blob) => { let url = window.URL.createObjectURL(blob); const img = document.createElement("img"); img.src = url; img.width = 200; document.body.appendChild(img); }); }; </script>
效果圖
方法補(bǔ)充
除了上文的方法,小編還為大家介紹了其他JavaScrip等比壓縮圖片的方法,希望對(duì)大家有所幫助
JS利用Canvas實(shí)現(xiàn)圖片等比例裁剪、壓縮
原理:
圖像壓縮有兩種方式,目前寫(xiě)的方法是兩者都支持且能夠共同處理
1.圖像尺寸裁剪,由大變小
2.尺寸不變,圖片質(zhì)量縮減
引用代碼:
if (!HTMLCanvasElement.prototype.toBlob) { Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', { value: function(callback, type, quality) { var canvas = this setTimeout(() => { var binStr = atob(canvas.toDataURL(type, quality).split(',')[1]) var len = binStr.length var arr = new Uint8Array(len) for (var i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i) } callback(new Blob([arr], { type: type || 'image/png' })) }) } }) } /** * 圖片壓縮 * @param {object} options 參數(shù) * @param {string} options.content 圖像內(nèi)容 * @param {number} options.maxWidth 最大寬度 * @param {number} options.maxHeight 最大高度 * @param {number} options.quality 圖像質(zhì)量 * @example rotateImage({ content: Img, maxWidth: 1000, maxHeight: 1000, quality: 0.8 }) * @returns {Promise<object>} 結(jié)果值 */ const compressionImage = function(options = {}) { if (!options || typeof options !== 'object') { throw new Error(`[compressionImage error]: options is not a object`) } if (!options.content || (typeof options.content !== 'string' && !(options.content instanceof File))) { throw new Error(`[compressionImage error]: options.content is not a string or file`) } if (typeof options.maxWidth !== 'number') { throw new Error(`[compressionImage error]: options.maxWidth is not a number`) } if (typeof options.maxHeight !== 'number') { throw new Error(`[compressionImage error]: options.maxHeight is not a number`) } if (typeof options.quality !== 'number') { throw new Error(`[compressionImage error]: options.quality is not a number`) } return new Promise(resolve => { const set = (content, type) => { const canvasDOM = document.createElement('canvas') const canvasContext = canvasDOM.getContext('2d') const img = new Image() img.src = content img.onload = () => { let targetWidth let targetHeight if (img.width > options.maxWidth && img.height > options.maxHeight) { const rate = Math.min(options.maxWidth / img.width, options.maxHeight / img.height) targetWidth = img.width * rate targetHeight = img.height * rate } else if (img.width > options.maxWidth) { targetWidth = options.maxWidth targetHeight = (options.maxWidth / img.width) * img.height } else if (img.height > options.maxHeight) { targetHeight = options.maxHeight targetWidth = (options.maxHeight / img.height) * img.width } else { targetWidth = img.width targetHeight = img.height } canvasDOM.width = targetWidth canvasDOM.height = targetHeight canvasContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, targetWidth, targetHeight) const url = canvasDOM.toDataURL(type, options.quality) const callback = blob => { resolve({ url, blob }) } canvasDOM.toBlob(callback, type, options.quality) } } if (options.content instanceof File) { const fileReader = new FileReader() fileReader.readAsDataURL(options.content) fileReader.onload = e => { set(e.target.result, options.content.type) } } else if (typeof options.content === 'string') { const fileContent = options.content.includes('base64,') ? options.content : `data:image/jpeg;base64,${options.content}` const fileType = options.content.includes('data:image/png;base64,') ? 'image/png' : options.content.includes('data:image/gif;base64,') ? 'image/gif' : 'image/jpeg' set(fileContent, fileType) } }) }
調(diào)用方式:
const { url, blob } = await compressionImage({ content: 'base64', //圖像base64或file文件 maxWidth: 1000, //最大寬度 maxHeight: 600, //最大高度 quality: 0.7 //圖像質(zhì)量,1為100%,建議選值0.95以下,1輸出后的圖像較大 }) console.log('壓縮后的base64內(nèi)容', url) console.log('壓縮后的blob文件', blob)
到此這篇關(guān)于JavaScrip實(shí)現(xiàn)圖片壓縮與分辨率等比例縮放的文章就介紹到這了,更多相關(guān)JavaScrip圖片等比縮放內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js中substring和substr的詳細(xì)介紹與用法
這篇文章介紹了js中substring和substr的用法,有需要的朋友可以參考一下2013-08-08String.prototype實(shí)現(xiàn)的一些javascript函數(shù)介紹
這篇文章主要是對(duì)String.prototype實(shí)現(xiàn)的一些javascript函數(shù)進(jìn)行了詳細(xì)的介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2013-11-11layui實(shí)現(xiàn)根據(jù)table數(shù)據(jù)判斷按鈕顯示情況的方法
今天小編就為大家分享一篇layui實(shí)現(xiàn)根據(jù)table數(shù)據(jù)判斷按鈕顯示情況的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-09-09Javascript 網(wǎng)頁(yè)黑白效果實(shí)現(xiàn)代碼(兼容IE/FF等)
今天在網(wǎng)上看到有人推薦的一個(gè)不錯(cuò)的方法,試了一下,效果還是可以的,可以自定義讓網(wǎng)頁(yè)的某一部分變成灰度顏色(黑白)。2010-04-04收集的一些Array及String原型對(duì)象的擴(kuò)展實(shí)現(xiàn)代碼
收集的一些Array及String原型對(duì)象的擴(kuò)展實(shí)現(xiàn)代碼,學(xué)習(xí)js的朋友可以參考下。并可以自定義的對(duì)字符串與array數(shù)據(jù),進(jìn)行擴(kuò)展。2010-12-12