You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

189 lines
5.9 KiB

  1. import EXIF from 'exif-js';
  2. const MAX_IMAGE_PIXELS = 2073600; // 1920x1080px
  3. const _browser_quirks = {};
  4. // Some browsers will automatically draw images respecting their EXIF orientation
  5. // while others won't, and the safest way to detect that is to examine how it
  6. // is done on a known image.
  7. // See https://github.com/w3c/csswg-drafts/issues/4666
  8. // and https://github.com/blueimp/JavaScript-Load-Image/commit/1e4df707821a0afcc11ea0720ee403b8759f3881
  9. const dropOrientationIfNeeded = (orientation) => new Promise(resolve => {
  10. switch (_browser_quirks['image-orientation-automatic']) {
  11. case true:
  12. resolve(1);
  13. break;
  14. case false:
  15. resolve(orientation);
  16. break;
  17. default:
  18. // black 2x1 JPEG, with the following meta information set:
  19. // - EXIF Orientation: 6 (Rotated 90° CCW)
  20. const testImageURL =
  21. 'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' +
  22. 'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' +
  23. 'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' +
  24. 'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAEAAgMBEQACEQEDEQH/x' +
  25. 'ABKAAEAAAAAAAAAAAAAAAAAAAALEAEAAAAAAAAAAAAAAAAAAAAAAQEAAAAAAAAAAAAAAAA' +
  26. 'AAAAAEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/8H//2Q==';
  27. const img = new Image();
  28. img.onload = () => {
  29. const automatic = (img.width === 1 && img.height === 2);
  30. _browser_quirks['image-orientation-automatic'] = automatic;
  31. resolve(automatic ? 1 : orientation);
  32. };
  33. img.onerror = () => {
  34. _browser_quirks['image-orientation-automatic'] = false;
  35. resolve(orientation);
  36. };
  37. img.src = testImageURL;
  38. }
  39. });
  40. // Some browsers don't allow reading from a canvas and instead return all-white
  41. // or randomized data. Use a pre-defined image to check if reading the canvas
  42. // works.
  43. const checkCanvasReliability = () => new Promise((resolve, reject) => {
  44. switch(_browser_quirks['canvas-read-unreliable']) {
  45. case true:
  46. reject('Canvas reading unreliable');
  47. break;
  48. case false:
  49. resolve();
  50. break;
  51. default:
  52. // 2×2 GIF with white, red, green and blue pixels
  53. const testImageURL =
  54. 'data:image/gif;base64,R0lGODdhAgACAKEDAAAA//8AAAD/AP///ywAAAAAAgACAAACA1wEBQA7';
  55. const refData =
  56. [255, 255, 255, 255, 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255];
  57. const img = new Image();
  58. img.onload = () => {
  59. const canvas = document.createElement('canvas');
  60. const context = canvas.getContext('2d');
  61. context.drawImage(img, 0, 0, 2, 2);
  62. const imageData = context.getImageData(0, 0, 2, 2);
  63. if (imageData.data.every((x, i) => refData[i] === x)) {
  64. _browser_quirks['canvas-read-unreliable'] = false;
  65. resolve();
  66. } else {
  67. _browser_quirks['canvas-read-unreliable'] = true;
  68. reject('Canvas reading unreliable');
  69. }
  70. };
  71. img.onerror = () => {
  72. _browser_quirks['canvas-read-unreliable'] = true;
  73. reject('Failed to load test image');
  74. };
  75. img.src = testImageURL;
  76. }
  77. });
  78. const getImageUrl = inputFile => new Promise((resolve, reject) => {
  79. if (window.URL && URL.createObjectURL) {
  80. try {
  81. resolve(URL.createObjectURL(inputFile));
  82. } catch (error) {
  83. reject(error);
  84. }
  85. return;
  86. }
  87. const reader = new FileReader();
  88. reader.onerror = (...args) => reject(...args);
  89. reader.onload = ({ target }) => resolve(target.result);
  90. reader.readAsDataURL(inputFile);
  91. });
  92. const loadImage = inputFile => new Promise((resolve, reject) => {
  93. getImageUrl(inputFile).then(url => {
  94. const img = new Image();
  95. img.onerror = (...args) => reject(...args);
  96. img.onload = () => resolve(img);
  97. img.src = url;
  98. }).catch(reject);
  99. });
  100. const getOrientation = (img, type = 'image/png') => new Promise(resolve => {
  101. if (type !== 'image/jpeg') {
  102. resolve(1);
  103. return;
  104. }
  105. EXIF.getData(img, () => {
  106. const orientation = EXIF.getTag(img, 'Orientation');
  107. if (orientation !== 1) {
  108. dropOrientationIfNeeded(orientation).then(resolve).catch(() => resolve(orientation));
  109. } else {
  110. resolve(orientation);
  111. }
  112. });
  113. });
  114. const processImage = (img, { width, height, orientation, type = 'image/png' }) => new Promise(resolve => {
  115. const canvas = document.createElement('canvas');
  116. if (4 < orientation && orientation < 9) {
  117. canvas.width = height;
  118. canvas.height = width;
  119. } else {
  120. canvas.width = width;
  121. canvas.height = height;
  122. }
  123. const context = canvas.getContext('2d');
  124. switch (orientation) {
  125. case 2: context.transform(-1, 0, 0, 1, width, 0); break;
  126. case 3: context.transform(-1, 0, 0, -1, width, height); break;
  127. case 4: context.transform(1, 0, 0, -1, 0, height); break;
  128. case 5: context.transform(0, 1, 1, 0, 0, 0); break;
  129. case 6: context.transform(0, 1, -1, 0, height, 0); break;
  130. case 7: context.transform(0, -1, -1, 0, height, width); break;
  131. case 8: context.transform(0, -1, 1, 0, 0, width); break;
  132. }
  133. context.drawImage(img, 0, 0, width, height);
  134. canvas.toBlob(resolve, type);
  135. });
  136. const resizeImage = (img, type = 'image/png') => new Promise((resolve, reject) => {
  137. const { width, height } = img;
  138. const newWidth = Math.round(Math.sqrt(MAX_IMAGE_PIXELS * (width / height)));
  139. const newHeight = Math.round(Math.sqrt(MAX_IMAGE_PIXELS * (height / width)));
  140. checkCanvasReliability()
  141. .then(getOrientation(img, type))
  142. .then(orientation => processImage(img, {
  143. width: newWidth,
  144. height: newHeight,
  145. orientation,
  146. type,
  147. }))
  148. .then(resolve)
  149. .catch(reject);
  150. });
  151. export default inputFile => new Promise((resolve) => {
  152. if (!inputFile.type.match(/image.*/) || inputFile.type === 'image/gif') {
  153. resolve(inputFile);
  154. return;
  155. }
  156. loadImage(inputFile).then(img => {
  157. if (img.width * img.height < MAX_IMAGE_PIXELS) {
  158. resolve(inputFile);
  159. return;
  160. }
  161. resizeImage(img, inputFile.type)
  162. .then(resolve)
  163. .catch(() => resolve(inputFile));
  164. }).catch(() => resolve(inputFile));
  165. });