@@ -8,7 +8,18 @@ interface Props {
88 language ?: string ;
99}
1010
11- // Compress image using Canvas API
11+ /**
12+ * Compress an image file using the Canvas API.
13+ * Resizes the image to fit within maxWidth x maxHeight while maintaining aspect ratio.
14+ * PNG images are converted to JPEG for better compression.
15+ *
16+ * @param file - The image file to compress
17+ * @param maxWidth - Maximum width in pixels (default: 1920)
18+ * @param maxHeight - Maximum height in pixels (default: 1920)
19+ * @param quality - JPEG compression quality from 0 to 1 (default: 0.85)
20+ * @returns Promise that resolves to a base64 data URL of the compressed image
21+ * @throws Error if image loading or canvas operations fail
22+ */
1223async function compressImage ( file : File , maxWidth : number = 1920 , maxHeight : number = 1920 , quality : number = 0.85 ) : Promise < string > {
1324 return new Promise ( ( resolve , reject ) => {
1425 const reader = new FileReader ( ) ;
@@ -44,10 +55,9 @@ async function compressImage(file: File, maxWidth: number = 1920, maxHeight: num
4455
4556 ctx . drawImage ( img , 0 , 0 , width , height ) ;
4657
47- // For PNG files, try to compress as JPEG if it results in smaller size
48- // For JPEG files, always use JPEG format
49- const mimeType = file . type === 'image/png' ? 'image/jpeg' : file . type ;
50- const dataUrl = canvas . toDataURL ( mimeType , quality ) ;
58+ // Convert all raster images to JPEG for consistent compression
59+ // JPEG provides good quality at significantly smaller file sizes
60+ const dataUrl = canvas . toDataURL ( 'image/jpeg' , quality ) ;
5161
5262 resolve ( dataUrl ) ;
5363 } ;
0 commit comments