用canvas对图片进行压缩
let canvas = document.createElement('canvas')
canvas.width = XXX
canvas.height = XXX
let ctx = canvas.getContext('2d')
ctx.drawImage(image , 0,0,widht ,height)
let data = canvas.toDataURL('image/png',0.8)
前端获取上传文件内容的方法: new FileReader()
input.addEventListener('change' , (e) => {
const [file] = e.target.files
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = (e)=> {
let base64 = e.target.result
compress(base64)
}
})
整体代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- input 上传文件类型,accept限制文件格式 -->
<input type="file" id="input" accept="image/*">
</body>
<script>
input.addEventListener('change', (e) => {
console.log(e)
const [file] = e.target.files
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = async (e) => {
const data = e.target.result
const _imageCur = new Image()
_imageCur.src = data
const base64 = await comapre(data)
const _image = new Image()
_image.src = base64
document.body.appendChild(_imageCur)
document.body.appendChild(_image)
}
async function comapre(base64, maxHeight = 500, maxWeight = 500) {
const { promise, resolve, reject } = Promise.withResolvers()
console.log(promise, '29')
let img = new Image()
img.src = base64
img.onload = () => {
let { isNeedCompress, radio, width, height } = getImageComputedSize({
isNeedCompress: false,
redio: 1,
width: img.width,
height: img.height,
maxHeight,
maxWeight
})
if (isNeedCompress) {
let canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, width, height)
const data = canvas.toDataURL('image/png', 0.8)
resolve(data)
} else {
resolve(base64)
}
}
return promise
}
function getImageComputedSize(option) {
let { isNeedCompress, radio, width, height, maxHeight, maxWeight } = option
if (width > height) {
if (width > maxWeight) {
radio = maxWeight / width
height = Math.round(height * radio)
width = maxWeight
isNeedCompress = true
}
} else {
if (height > maxHeight) {
radio = maxHeight / height
height = maxHeight
width = Math.round(width * radio)
isNeedCompress = true
}
}
return {
isNeedCompress, radio, width, height
}
}
})
</script>
</html>