Files
otunes/apps/web/lib/resize-image.ts
T
joshuafhigginsandClaude Opus 5.5 Verified 86235a11c4 feat: playlist cover artwork
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>
2026-11-19 18:11:59 -05:00

63 lines
1.5 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.
/**
* 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 })
}