image_utils.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* Copyright 2022 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import { FeatureTest } from "./util.js";
  16. function applyMaskImageData({
  17. src,
  18. srcPos = 0,
  19. dest,
  20. destPos = 0,
  21. width,
  22. height,
  23. inverseDecode = false,
  24. }) {
  25. const opaque = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  26. const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
  27. const widthInSource = width >> 3;
  28. const widthRemainder = width & 7;
  29. const srcLength = src.length;
  30. dest = new Uint32Array(dest.buffer);
  31. for (let i = 0; i < height; i++) {
  32. for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
  33. const elem = srcPos < srcLength ? src[srcPos] : 255;
  34. dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
  35. dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
  36. dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
  37. dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
  38. dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
  39. dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
  40. dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
  41. dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
  42. }
  43. if (widthRemainder === 0) {
  44. continue;
  45. }
  46. const elem = srcPos < srcLength ? src[srcPos++] : 255;
  47. for (let j = 0; j < widthRemainder; j++) {
  48. dest[destPos++] = elem & (1 << (7 - j)) ? oneMapping : zeroMapping;
  49. }
  50. }
  51. return { srcPos, destPos };
  52. }
  53. export { applyMaskImageData };