all files / src/ loadImage.js

4.17% Statements 1/24
0% Branches 0/2
0% Functions 0/7
4.17% Lines 1/24
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 68 69 70                                                                                                                                         
import { external } from './externalModules.js';
import arrayBufferToImage from './arrayBufferToImage.js';
import createImage from './createImage.js';
 
//
// This is a cornerstone image loader for web images such as PNG and JPEG
//
let options = {
  // callback allowing customization of the xhr (e.g. adding custom auth headers, cors, etc)
  beforeSend (/* xhr */) {}
};
 
 
// Loads an image given a url to an image
export function loadImage (imageId) {
  const cornerstone = external.cornerstone;
 
  const xhr = new XMLHttpRequest();
 
  xhr.open('GET', imageId, true);
  xhr.responseType = 'arraybuffer';
  options.beforeSend(xhr);
 
  xhr.onprogress = function (oProgress) {
    if (oProgress.lengthComputable) {
      // evt.loaded the bytes browser receive
      // evt.total the total bytes set by the header
      const loaded = oProgress.loaded;
      const total = oProgress.total;
      const percentComplete = Math.round((loaded / total) * 100);
 
      const eventData = {
        imageId,
        loaded,
        total,
        percentComplete
      };
 
      cornerstone.triggerEvent(cornerstone.events, 'cornerstoneimageloadprogress', eventData);
    }
  };
 
  const promise = new Promise((resolve, reject) => {
    xhr.onload = function () {
      const imagePromise = arrayBufferToImage(this.response);
 
      imagePromise.then((image) => {
        const imageObject = createImage(image, imageId);
 
        resolve(imageObject);
      }, reject);
    };
 
    xhr.send();
  });
 
  const cancelFn = () => {
    xhr.abort();
  };
 
  return {
    promise,
    cancelFn
  };
}
 
export function configure (opts) {
  options = opts;
}