All files / src/renderer/lib/tiles readCanvasToTiles.ts

0% Statements 0/10
0% Branches 0/1
0% Functions 0/1
0% Lines 0/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                                                                     
import {
  ImageIndexFunction,
  IndexedImage,
  makeIndexedImage,
  pixelDataToIndexedImage,
} from "shared/lib/tiles/indexedImage";
 
/**
 * Load the given ImageBitmap data into an IndexedImage using the supplied index function.
 *
 * Uses Canvas API and should be run from a browser context. Consider using readFileToIndexedImage instead if calling from Node.
 *
 * @param img ImageBitmap data, can access this using fetch API on a URL e.g. `const img = await fetch(src).then((r) => r.blob())`
 * @param indexFn Function to map an individual RGB pixel value to an 8-bit indexed value
 * @returns A new IndexedImage representing the image data provided
 */
export const imageToIndexedImage = (
  img: ImageBitmap,
  indexFn: ImageIndexFunction
): IndexedImage => {
  const canvas = new OffscreenCanvas(img.width, img.height);
  const ctx = canvas.getContext("2d");
  Iif (!ctx) {
    return makeIndexedImage(img.width, img.height);
  }
  ctx.drawImage(img, 0, 0);
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  return pixelDataToIndexedImage(
    img.width,
    img.height,
    imageData.data,
    indexFn
  );
};