這篇文章將為大家詳細講解有關利用JavaScript如何實現圖片壓縮功能,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

具體內容如下
<!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
// 目標尺寸
var targetWidth = originWidth, targetHeight = originHeight;
//當原始尺寸大于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 轉為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')
//在頁面預覽原圖片
var div1 = document.createElement('div')
div1.innerText = '原圖:'
document.body.appendChild(div1)
document.body.appendChild(img)
//canvas預覽
var div2 = document.createElement('div')
div2.innerText = 'canvas圖:'
document.body.appendChild(div2)
document.body.appendChild(canvas)
}
</script>
</body>
</html>
當前標題:利用JavaScript如何實現圖片壓縮功能-創新互聯
分享URL:http://www.yijiale78.com/article46/cdjheg.html
成都網站建設公司_創新互聯,為您提供Google、App開發、虛擬主機、小程序開發、品牌網站建設、面包屑導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯