63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
/**
|
||
* Downscales an image to `size`×`size` (center-cropped cover) and returns a
|
||
* base64 data URL. JPEG, unless `keepLossless` and the file is PNG or WebP.
|
||
*/
|
||
export function resizeImageToDataUrl(
|
||
file: File,
|
||
size: number,
|
||
{ keepLossless = false } = {}
|
||
): 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 = size
|
||
canvas.height = size
|
||
|
||
const ctx = canvas.getContext("2d")
|
||
if (!ctx) {
|
||
reject(new Error("Could not process image"))
|
||
return
|
||
}
|
||
|
||
const scale = Math.max(size / image.width, size / image.height)
|
||
const width = image.width * scale
|
||
const height = image.height * scale
|
||
ctx.drawImage(
|
||
image,
|
||
(size - width) / 2,
|
||
(size - height) / 2,
|
||
width,
|
||
height
|
||
)
|
||
|
||
const outputType =
|
||
keepLossless &&
|
||
(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
|
||
})
|
||
}
|
||
|
||
export function resizeProfileImageToDataUrl(file: File) {
|
||
return resizeImageToDataUrl(file, 256, { keepLossless: true })
|
||
}
|