| 164 | } |
| 165 | |
| 166 | function loadImageAndSendDataBack(src, sendResponse) { |
| 167 | // Load image (with crossOrigin set to anonymous so that it can be used in a |
| 168 | // canvas later). |
| 169 | const img = new Image(); |
| 170 | img.crossOrigin = 'anonymous'; |
| 171 | img.onerror = function(e) { |
| 172 | console.warn(`Could not load image from external source ${src}.`); |
| 173 | sendResponse({rawImageData: undefined}); |
| 174 | return; |
| 175 | }; |
| 176 | img.onload = function(e) { |
| 177 | if ((img.height && img.height > MIN_IMG_SIZE) || |
| 178 | (img.width && img.width > MIN_IMG_SIZE)) { |
| 179 | img.width = IMAGE_SIZE; |
| 180 | img.height = IMAGE_SIZE; |
| 181 | // When image is loaded, render it to a canvas and send its ImageData back |
| 182 | // to the service worker. |
| 183 | const canvas = new OffscreenCanvas(img.width, img.height); |
| 184 | const ctx = canvas.getContext('2d'); |
| 185 | ctx.drawImage(img, 0, 0); |
| 186 | const imageData = ctx.getImageData(0, 0, img.width, img.height); |
| 187 | sendResponse({ |
| 188 | rawImageData: Array.from(imageData.data), |
| 189 | width: img.width, |
| 190 | height: img.height, |
| 191 | }); |
| 192 | return; |
| 193 | } |
| 194 | // Fail out if either dimension is less than MIN_IMG_SIZE. |
| 195 | console.warn(`Image size too small. [${img.height} x ${ |
| 196 | img.width}] vs. minimum [${MIN_IMG_SIZE} x ${MIN_IMG_SIZE}]`); |
| 197 | sendResponse({rawImageData: undefined}); |
| 198 | }; |
| 199 | img.src = src; |
| 200 | } |