format-normaliser.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. "use strict";
  2. function dePalette(indata, outdata, width, height, palette) {
  3. let pxPos = 0;
  4. // use values from palette
  5. for (let y = 0; y < height; y++) {
  6. for (let x = 0; x < width; x++) {
  7. let color = palette[indata[pxPos]];
  8. if (!color) {
  9. throw new Error("index " + indata[pxPos] + " not in palette");
  10. }
  11. for (let i = 0; i < 4; i++) {
  12. outdata[pxPos + i] = color[i];
  13. }
  14. pxPos += 4;
  15. }
  16. }
  17. }
  18. function replaceTransparentColor(indata, outdata, width, height, transColor) {
  19. let pxPos = 0;
  20. for (let y = 0; y < height; y++) {
  21. for (let x = 0; x < width; x++) {
  22. let makeTrans = false;
  23. if (transColor.length === 1) {
  24. if (transColor[0] === indata[pxPos]) {
  25. makeTrans = true;
  26. }
  27. } else if (
  28. transColor[0] === indata[pxPos] &&
  29. transColor[1] === indata[pxPos + 1] &&
  30. transColor[2] === indata[pxPos + 2]
  31. ) {
  32. makeTrans = true;
  33. }
  34. if (makeTrans) {
  35. for (let i = 0; i < 4; i++) {
  36. outdata[pxPos + i] = 0;
  37. }
  38. }
  39. pxPos += 4;
  40. }
  41. }
  42. }
  43. function scaleDepth(indata, outdata, width, height, depth) {
  44. let maxOutSample = 255;
  45. let maxInSample = Math.pow(2, depth) - 1;
  46. let pxPos = 0;
  47. for (let y = 0; y < height; y++) {
  48. for (let x = 0; x < width; x++) {
  49. for (let i = 0; i < 4; i++) {
  50. outdata[pxPos + i] = Math.floor(
  51. (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5
  52. );
  53. }
  54. pxPos += 4;
  55. }
  56. }
  57. }
  58. module.exports = function (indata, imageData) {
  59. let depth = imageData.depth;
  60. let width = imageData.width;
  61. let height = imageData.height;
  62. let colorType = imageData.colorType;
  63. let transColor = imageData.transColor;
  64. let palette = imageData.palette;
  65. let outdata = indata; // only different for 16 bits
  66. if (colorType === 3) {
  67. // paletted
  68. dePalette(indata, outdata, width, height, palette);
  69. } else {
  70. if (transColor) {
  71. replaceTransparentColor(indata, outdata, width, height, transColor);
  72. }
  73. // if it needs scaling
  74. if (depth !== 8) {
  75. // if we need to change the buffer size
  76. if (depth === 16) {
  77. outdata = Buffer.alloc(width * height * 4);
  78. }
  79. scaleDepth(indata, outdata, width, height, depth);
  80. }
  81. }
  82. return outdata;
  83. };