@@ -81,6 +81,8 @@ function nearestPaletteIndex(sample, palette) {
8181 }
8282 return best ;
8383}
84+ /** Upper limit of the sample window radius, in image pixels. */
85+ const MAX_SAMPLE_RADIUS = 16 ;
8486/**
8587 * Sample and classify a `width` x `height` grid.
8688 *
@@ -101,16 +103,23 @@ export function classifyGrid(image, width, height, transform, palette) {
101103 const p2 = transform . transformPoint ( 0.5 , 1.5 ) ;
102104 const stepX = Math . hypot ( p1 . x - p0 . x , p1 . y - p0 . y ) ;
103105 const stepY = Math . hypot ( p2 . x - p0 . x , p2 . y - p0 . y ) ;
104- const rx = Math . max ( 1 , Math . round ( stepX / 4 ) ) ;
105- const ry = Math . max ( 1 , Math . round ( stepY / 4 ) ) ;
106+ if ( ! Number . isFinite ( stepX ) || ! Number . isFinite ( stepY ) ) {
107+ throw new NotFoundError ( 'Sampling grid has a non-finite or degenerate transform' ) ;
108+ }
109+ // The radius has a fixed upper limit, so the work for each module stays
110+ // within a fixed budget for any caller geometry.
111+ const rx = Math . min ( MAX_SAMPLE_RADIUS , Math . max ( 1 , Math . round ( stepX / 4 ) ) ) ;
112+ const ry = Math . min ( MAX_SAMPLE_RADIUS , Math . max ( 1 , Math . round ( stepY / 4 ) ) ) ;
106113 for ( let y = 0 ; y < height ; y ++ ) {
107114 for ( let x = 0 ; x < width ; x ++ ) {
108115 const c = transform . transformPoint ( x + 0.5 , y + 0.5 ) ;
109- const cx = c . x | 0 ;
110- const cy = c . y | 0 ;
111- if ( cx < 0 || cy < 0 || cx >= image . width || cy >= image . height ) {
116+ // Check the real values before the integer conversion: `|0` wraps large
117+ // values and turns NaN into 0.
118+ if ( ! ( c . x >= 0 && c . y >= 0 && c . x < image . width && c . y < image . height ) ) {
112119 throw new NotFoundError ( `Sampling grid escapes the image at module (${ x } , ${ y } )` ) ;
113120 }
121+ const cx = c . x | 0 ;
122+ const cy = c . y | 0 ;
114123 let sumR = 0 , sumG = 0 , sumB = 0 , count = 0 ;
115124 for ( let dy = - ry ; dy <= ry ; dy ++ ) {
116125 for ( let dx = - rx ; dx <= rx ; dx ++ ) {
0 commit comments