@@ -14,6 +14,8 @@ const formats: Record<Format, `image/${string}`> = {
14
14
webp : "image/webp" ,
15
15
}
16
16
17
+ const svgRegex = / < s v g w i d t h = " ( \d + ) " h e i g h t = " ( \d + ) " [ \S \d \s ] * /
18
+
17
19
export const GET : APIRoute = async ( { params } ) => {
18
20
const format = params [ "format" ] as Format ;
19
21
let category = params [ "category" ] as Category ;
@@ -31,12 +33,13 @@ export const GET: APIRoute = async ({ params }) => {
31
33
}
32
34
}
33
35
36
+ const targetHeight = heights [ size ] ;
34
37
35
38
const img = await readFile ( `src/assets/${ category } /${ slug } /${ size } .svg` ) ;
36
39
37
40
const isSVG = format === "svg" ;
38
41
if ( ! isSVG ) {
39
- const formatted = sharp ( img ) . resize ( { height : heights [ size ] } ) ;
42
+ const formatted = sharp ( img ) . resize ( { height : targetHeight } ) ;
40
43
41
44
// Set background to white if image doesn't support transparency
42
45
if ( [ "jpeg" , "jpg" ] . includes ( format ) ) formatted . flatten ( { background : "#FFFFFF" } )
@@ -45,7 +48,19 @@ export const GET: APIRoute = async ({ params }) => {
45
48
return new Response ( await formatted . toFormat ( format ) . toBuffer ( ) , { headers : { "Content-Type" : formats [ format ] } } ) ;
46
49
}
47
50
48
- return new Response ( img , { headers : { "Content-Type" : formats [ format ] } } ) ;
51
+ const svg = img . toString ( ) ;
52
+
53
+ const [ _ , width , height ] = svgRegex . exec ( svg ) as string [ ] ;
54
+ if ( ! width || ! height ) return new Response ( img , { headers : { "Content-Type" : formats [ format ] } } ) ;
55
+
56
+ const widthInt = Number . parseInt ( width , 10 ) ;
57
+ const heightInt = Number . parseInt ( height , 10 ) ;
58
+
59
+ const scaleFactor = targetHeight / heightInt ;
60
+ if ( Number . isNaN ( scaleFactor ) ) throw new Error ( "Scale factor is NaN" ) ;
61
+
62
+ const newWidth = widthInt * scaleFactor ;
63
+ return new Response ( svg . replace ( / < s v g w i d t h = " ( \d + ) " h e i g h t = " ( \d + ) " / , `<svg width="${ newWidth } " height="${ targetHeight } "` ) , { headers : { "Content-Type" : formats [ format ] } } ) ;
49
64
}
50
65
51
66
export const prerender = true ;
0 commit comments