Files
otunes/lib/resize-profile-image.ts
T

50 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const PROFILE_IMAGE_SIZE = 256
/**
* Downscales an image to 256×256 (center-cropped cover) and returns a base64 data URL.
*/
export function resizeProfileImageToDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(file)
const image = new Image()
image.onload = () => {
URL.revokeObjectURL(url)
const canvas = document.createElement("canvas")
canvas.width = PROFILE_IMAGE_SIZE
canvas.height = PROFILE_IMAGE_SIZE
const ctx = canvas.getContext("2d")
if (!ctx) {
reject(new Error("Could not process image"))
return
}
const scale = Math.max(
PROFILE_IMAGE_SIZE / image.width,
PROFILE_IMAGE_SIZE / image.height
)
const width = image.width * scale
const height = image.height * scale
const x = (PROFILE_IMAGE_SIZE - width) / 2
const y = (PROFILE_IMAGE_SIZE - height) / 2
ctx.drawImage(image, x, y, width, height)
const outputType =
file.type === "image/png" || file.type === "image/webp"
? "image/png"
: "image/jpeg"
resolve(canvas.toDataURL(outputType, outputType === "image/jpeg" ? 0.9 : undefined))
}
image.onerror = () => {
URL.revokeObjectURL(url)
reject(new Error("Could not load image"))
}
image.src = url
})
}