<!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
>