1import { MimeTypeImage } from '$lib/enums';
2
3/**
4 * Convert an SVG base64 data URL to a PNG data URL
5 * @param base64UrlSvg - The SVG base64 data URL to convert
6 * @param backgroundColor - Background color for the PNG (default: 'white')
7 * @returns Promise resolving to PNG data URL
8 */
9export function svgBase64UrlToPngDataURL(
10 base64UrlSvg: string,
11 backgroundColor: string = 'white'
12): Promise<string> {
13 return new Promise((resolve, reject) => {
14 try {
15 const img = new Image();
16
17 img.onload = () => {
18 const canvas = document.createElement('canvas');
19 const ctx = canvas.getContext('2d');
20
21 if (!ctx) {
22 reject(new Error('Failed to get 2D canvas context.'));
23 return;
24 }
25
26 const targetWidth = img.naturalWidth || 300;
27 const targetHeight = img.naturalHeight || 300;
28
29 canvas.width = targetWidth;
30 canvas.height = targetHeight;
31
32 if (backgroundColor) {
33 ctx.fillStyle = backgroundColor;
34 ctx.fillRect(0, 0, canvas.width, canvas.height);
35 }
36 ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
37
38 resolve(canvas.toDataURL(MimeTypeImage.PNG));
39 };
40
41 img.onerror = () => {
42 reject(new Error('Failed to load SVG image. Ensure the SVG data is valid.'));
43 };
44
45 img.src = base64UrlSvg;
46 } catch (error) {
47 const message = error instanceof Error ? error.message : String(error);
48 const errorMessage = `Error converting SVG to PNG: ${message}`;
49 console.error(errorMessage, error);
50 reject(new Error(errorMessage));
51 }
52 });
53}
54
55/**
56 * Check if a file is an SVG based on its MIME type
57 * @param file - The file to check
58 * @returns True if the file is an SVG
59 */
60export function isSvgFile(file: File): boolean {
61 return file.type === MimeTypeImage.SVG;
62}
63
64/**
65 * Check if a MIME type represents an SVG
66 * @param mimeType - The MIME type to check
67 * @returns True if the MIME type is image/svg+xml
68 */
69export function isSvgMimeType(mimeType: string): boolean {
70 return mimeType === MimeTypeImage.SVG;
71}