//通过canvas压缩图像
const compressImage = (file: File): Promise<File> => {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = (e: ProgressEvent<FileReader>) => {
const img = new Image()
img.src = e.target?.result as string
img.onload = () => {
const canvas = document.createElement("canvas")
const ctx = canvas.getContext("2d")
const maxWidth = 800
const scale = maxWidth / img.width
canvas.width = img.width * scale
canvas.height = img.height * scale
ctx?.drawImage(img, 0, 0, canvas.width, canvas.height)
canvas.toBlob(blob => {
if (blob) {
const compressedFile = new File([blob], file.name, { type: file.type })
resolve(compressedFile)
} else {
reject(new Error("Failed to create Blob."))
}
}, file.type)
}
}
reader.readAsDataURL(file)
})
}
前端通过canvas压缩图片
最新推荐文章于 2024-05-16 11:12:50 发布