Kernel
function compressImage (fileObj) {
const WIDTH = 1200
const QUALITY = 0.6
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.readAsDataURL(fileObj)
reader.onload = function (e) {
let image = new Image()
image.src = e.target.result
image.onload = function () {
let canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
ratio = image.height / image.width
canvas.width = WIDTH
canvas.height = WIDTH * ratio
context.drawImage(image, 0, 0, canvas.width, canvas.height)
canvas.toBlob(blob => {
resolve(blob)
}, 'image/jpeg', QUALITY)
}
}
})
}
The demo page
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>压缩图片demo</title>
</head>
<body>
<img id="img" src="">
<input type="file" onchange="test(this.files[0])">
</body>
<script>
function compressImage(fileObj) {
const WIDTH = 1200
const QUALITY = 0.6
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.readAsDataURL(fileObj)
reader.onload = function (e) {
let image = new Image()
image.src = e.target.result
image.onload = function () {
let canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
ratio = image.height / image.width
canvas.width = WIDTH
canvas.height = WIDTH * ratio
context.drawImage(image, 0, 0, canvas.width, canvas.height)
canvas.toBlob(blob => {
resolve(blob)
}, 'image/jpeg', QUALITY)
}
}
})
}
function test(file) {
compressImage(file).then(result => {
console.log(result)
let img_src = URL.createObjectURL(result)
document.getElementById('img').src = img_src
})
}
</script>
</html>