All files / Sources/Common/Core/ImageHelper index.js

52.38% Statements 11/21
64.28% Branches 9/14
50% Functions 1/2
52.38% Lines 11/21

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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                        95x 95x 95x             95x 95x 95x 95x                 95x       95x 95x   95x                                                    
import vtkImageData from 'vtk.js/Sources/Common/DataModel/ImageData';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
 
/**
 * Takes a canvas and converts it to a vtkImageData.
 *
 * Optionally supply a bounding box to get a particular subset of the canvas.
 *
 * @param canvas       The HTML canvas to convert
 * @param boundingBox  A bounding box of type [top, left, width, height]
 */
function canvasToImageData(canvas, boundingBox = [0, 0, 0, 0]) {
  const [top, left, width, height] = boundingBox;
  const ctxt = canvas.getContext('2d');
  const idata = ctxt.getImageData(
    top,
    left,
    width || canvas.width,
    height || canvas.height
  );
 
  const imageData = vtkImageData.newInstance({ type: 'vtkImageData' });
  imageData.setOrigin(0, 0, 0);
  imageData.setSpacing(1, 1, 1);
  imageData.setExtent(
    0,
    (width || canvas.width) - 1,
    0,
    (height || canvas.height) - 1,
    0,
    0
  );
 
  const scalars = vtkDataArray.newInstance({
    numberOfComponents: 4,
    values: new Uint8Array(idata.data.buffer),
  });
  scalars.setName('scalars');
  imageData.getPointData().setScalars(scalars);
 
  return imageData;
}
 
/**
 * Converts an Image object to a vtkImageData.
 */
function imageToImageData(
  image,
  transform = { flipX: false, flipY: false, rotate: 0 }
) {
  const canvas = document.createElement('canvas');
  canvas.width = image.width;
  canvas.height = image.height;
 
  const ctx = canvas.getContext('2d');
 
  const { flipX, flipY, rotate } = transform;
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.scale(flipX ? -1 : 1, flipY ? -1 : 1);
  ctx.rotate((rotate * Math.PI) / 180);
  ctx.drawImage(image, -image.width / 2, -image.height / 2);
 
  return canvasToImageData(canvas);
}
 
export default { canvasToImageData, imageToImageData };