feat: add logo file preparation with SVG to PNG conversion

This commit is contained in:
rajun 2026-10-27 16:28:52 +05:30
parent a8c10d34d6
commit 1ba3d33a61

View File

@ -0,0 +1,43 @@
import { LOGO_MAX_BYTES, LOGO_RASTER_MAX_SIZE, LOGO_TYPES } from '~/data/projects/constants';
type LogoResult = { file: File } | { error: string };
export const logoAccept = (allowSvg: boolean) =>
[LOGO_TYPES.png, LOGO_TYPES.webp, ...(allowSvg ? [LOGO_TYPES.svg] : [])].join(',');
export const logoFormatsLabel = (allowSvg: boolean) => (allowSvg ? 'PNG, WebP or SVG' : 'PNG or WebP');
// Draws an SVG onto a canvas and returns it as a PNG, so scripts inside the SVG are never stored
async function rasterizeSvg(file: File): Promise<File> {
const url = URL.createObjectURL(file);
try {
const image = new Image();
image.src = url;
await image.decode();
const width = image.naturalWidth || LOGO_RASTER_MAX_SIZE;
const height = image.naturalHeight || LOGO_RASTER_MAX_SIZE;
const scale = LOGO_RASTER_MAX_SIZE / Math.max(width, height);
const canvas = document.createElement('canvas');
canvas.width = Math.round(width * scale);
canvas.height = Math.round(height * scale);
canvas.getContext('2d')?.drawImage(image, 0, 0, canvas.width, canvas.height);
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, LOGO_TYPES.png));
if (!blob) throw new Error('Could not convert the SVG');
return new File([blob], file.name.replace(/\.svg$/i, '.png'), { type: LOGO_TYPES.png });
} finally {
URL.revokeObjectURL(url);
}
}
export async function prepareLogoFile(file: File, allowSvg: boolean): Promise<LogoResult> {
if (file.size > LOGO_MAX_BYTES) return { error: 'The logo must be 2 MB or smaller' };
if (file.type === LOGO_TYPES.png || file.type === LOGO_TYPES.webp) return { file };
if (file.type === LOGO_TYPES.svg && allowSvg) {
try {
return { file: await rasterizeSvg(file) };
} catch {
return { error: 'This SVG could not be read. Try a PNG instead.' };
}
}
return { error: `Use a ${logoFormatsLabel(allowSvg)} file` };
}