22 lines
945 B
TypeScript
22 lines
945 B
TypeScript
/** Downscale an image file to a JPEG data URL with its long side at most `max` pixels. */
|
|
export async function resizeImage(file: File, max: number, quality = 0.82): Promise<string> {
|
|
const url = URL.createObjectURL(file)
|
|
try {
|
|
const image = new Image()
|
|
image.src = url
|
|
await image.decode()
|
|
const scale = Math.min(1, max / Math.max(image.naturalWidth, image.naturalHeight))
|
|
const canvas = document.createElement('canvas')
|
|
canvas.width = Math.max(1, Math.round(image.naturalWidth * scale))
|
|
canvas.height = Math.max(1, Math.round(image.naturalHeight * scale))
|
|
const context = canvas.getContext('2d')
|
|
if (!context) throw new Error('Canvas unavailable')
|
|
context.fillStyle = '#11151d'
|
|
context.fillRect(0, 0, canvas.width, canvas.height)
|
|
context.drawImage(image, 0, 0, canvas.width, canvas.height)
|
|
return canvas.toDataURL('image/jpeg', quality)
|
|
} finally {
|
|
URL.revokeObjectURL(url)
|
|
}
|
|
}
|