all files / src/imageLoader/wadors/ getPixelData.js

0% Statements 0/31
0% Branches 0/15
0% Functions 0/6
0% Lines 0/31
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 71 72 73 74 75 76 77 78 79 80 81 82 83                                                                                                                                                                     
import { xhrRequest } from '../internal/index.js';
import findIndexOfString from './findIndexOfString.js';
 
function findBoundary (header) {
  for (let i = 0; i < header.length; i++) {
    if (header[i].substr(0, 2) === '--') {
      return header[i];
    }
  }
}
 
function findContentType (header) {
  for (let i = 0; i < header.length; i++) {
    if (header[i].substr(0, 13) === 'Content-Type:') {
      return header[i].substr(13).trim();
    }
  }
}
 
function uint8ArrayToString (data, offset, length) {
  offset = offset || 0;
  length = length || data.length - offset;
  let str = '';
 
  for (let i = offset; i < offset + length; i++) {
    str += String.fromCharCode(data[i]);
  }
 
  return str;
}
 
function getPixelData (uri, imageId, mediaType = 'application/octet-stream') {
  const headers = {
    accept: mediaType
  };
 
  return new Promise((resolve, reject) => {
    const loadPromise = xhrRequest(uri, imageId, headers);
 
    loadPromise.then(function (imageFrameAsArrayBuffer/* , xhr*/) {
 
      // request succeeded, Parse the multi-part mime response
      const response = new Uint8Array(imageFrameAsArrayBuffer);
 
      // First look for the multipart mime header
      const tokenIndex = findIndexOfString(response, '\r\n\r\n');
 
      if (tokenIndex === -1) {
        reject(new Error('invalid response - no multipart mime header'));
      }
      const header = uint8ArrayToString(response, 0, tokenIndex);
      // Now find the boundary  marker
      const split = header.split('\r\n');
      const boundary = findBoundary(split);
 
      if (!boundary) {
        reject(new Error('invalid response - no boundary marker'));
      }
      const offset = tokenIndex + 4; // skip over the \r\n\r\n
 
      // find the terminal boundary marker
      const endIndex = findIndexOfString(response, boundary, offset);
 
      if (endIndex === -1) {
        reject(new Error('invalid response - terminating boundary not found'));
      }
 
      // Remove \r\n from the length
      const length = endIndex - offset - 2;
 
      // return the info for this pixel data
      resolve({
        contentType: findContentType(split),
        imageFrame: {
          pixelData: new Uint8Array(imageFrameAsArrayBuffer, offset, length)
        }
      });
    });
  });
}
 
export default getPixelData;