這篇文章將為大家詳細(xì)講解有關(guān)利用JavaScript如何實現(xiàn)圖片壓縮功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
具體內(nèi)容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>壓縮圖片</title> </head> <body> <input id='file' type="file"> <script> var eleFile = document.querySelector('#file') var file; var render = new FileReader(), img = new Image(); render.onload = function(e) { img.src = e.target.result } // 獲取圖片文件 eleFile.addEventListener('change', function(e) { file = e.target.files[0]; if(file.type.indexOf('image') === 0) { //讀取文件,并返回一個URL格式的Base64字符串 render.readAsDataURL(file) } }) //使用canvas把圖片畫出來 var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); img.onload = function() { //原始尺寸 var originWidth = this.width; var originHeight = this.height; //較大尺寸限制 var maxWidth = 200, maxHeight = 200 // 目標(biāo)尺寸 var targetWidth = originWidth, targetHeight = originHeight; //當(dāng)原始尺寸大于200*200時候 if(originWidth > maxWidth || originHeight > maxHeight) { if(originWidth / originHeight > maxWidth / maxHeight) { //更寬 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 轉(zhuǎn)為blob并上傳 canvas.toBlob(function(blob) { try { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() {{ if(xhr.status == 200) { } }} //開始上傳 xhr.open('POST','upload.php', true); xhr.send(blob) } catch (error) { console.log(error) } }, file.type || 'image/png') //在頁面預(yù)覽原圖片 var div1 = document.createElement('div') div1.innerText = '原圖:' document.body.appendChild(div1) document.body.appendChild(img) //canvas預(yù)覽 var div2 = document.createElement('div') div2.innerText = 'canvas圖:' document.body.appendChild(div2) document.body.appendChild(canvas) } </script> </body> </html>
當(dāng)前標(biāo)題:利用JavaScript如何實現(xiàn)圖片壓縮功能-創(chuàng)新互聯(lián)
分享URL:http://chinadenli.net/article46/cdjheg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、App開發(fā)、虛擬主機、小程序開發(fā)、品牌網(wǎng)站建設(shè)、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)