Playlists draw a 2x2 of their first albums automatically. Owners can pick from random grids, reshuffle, or upload an image on web and mobile. Covers are rendered once into Convex storage and redrawn only when the playlist's albums change. Web and iPad sidebars show playlist covers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 })
|
||
}
|