format-normaliser.js 2.2 KB

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