console
const $ = s => document.querySelector(s)
let result_url
const page = new (class {
get result_url() {
return result_url
}
set result_url(val) {
$("#img").src = val
result_url = val
}
changeInput(e) {
$("#download").style.display = "none"
let reader = new FileReader()
let img = new Image()
let canvas = document.createElement("canvas")
let ctx = canvas.getContext("2d")
let file = e.target.files[0]
reader.readAsDataURL(file)
reader.onload = (e) => {
img.src = e.target.result
}
img.onload = (_) => {
let width = img.width
let height = img.height
if (width > 1200) {
height = (height * 1200) / width
width = 1200
}
canvas.width = width
canvas.height = height
ctx.clearRect(0, 0, width, height)
ctx.drawImage(img, 0, 0, width, height)
this.result_url = canvas.toDataURL("image/jpeg", 0.2)
$("#download").style.display = "block"
$("#download").href = this.result_url
$("#download").download = "图片"
}
}
})()
<div class="compress">
JSRUN坑爹,无法下载,请自行源码尝试
<input
id="input"
type="file"
onchange="page.changeInput(event)"
accept="image/*"
/>
<a
id="download"
style="display: none; margin-top: var(--main_gap)"
href="#"
download
>
<p>点击图片下载</p>
<img id="img" class="preview" src="#" alt="img" />
</a>
</div>
.compress {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}