前端通过canvas压缩图片

//通过canvas压缩图像
const compressImage = (file: File): Promise => {
	return new Promise((resolve, reject) => {
		const reader = new FileReader()

		reader.onload = (e: ProgressEvent) => {
			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)
	})
}

你可能感兴趣的:(前端,算法,javascript)