encoder.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * @author shaozilee
  3. *
  4. * BMP format encoder,encode 24bit BMP
  5. * Not support quality compression
  6. *
  7. */
  8. function BmpEncoder(imgData){
  9. this.buffer = imgData.data;
  10. this.width = imgData.width;
  11. this.height = imgData.height;
  12. this.extraBytes = this.width%4;
  13. this.rgbSize = this.height*(3*this.width+this.extraBytes);
  14. this.headerInfoSize = 40;
  15. this.data = [];
  16. /******************header***********************/
  17. this.flag = "BM";
  18. this.reserved = 0;
  19. this.offset = 54;
  20. this.fileSize = this.rgbSize+this.offset;
  21. this.planes = 1;
  22. this.bitPP = 24;
  23. this.compress = 0;
  24. this.hr = 0;
  25. this.vr = 0;
  26. this.colors = 0;
  27. this.importantColors = 0;
  28. }
  29. BmpEncoder.prototype.encode = function() {
  30. var tempBuffer = new Buffer(this.offset+this.rgbSize);
  31. this.pos = 0;
  32. tempBuffer.write(this.flag,this.pos,2);this.pos+=2;
  33. tempBuffer.writeUInt32LE(this.fileSize,this.pos);this.pos+=4;
  34. tempBuffer.writeUInt32LE(this.reserved,this.pos);this.pos+=4;
  35. tempBuffer.writeUInt32LE(this.offset,this.pos);this.pos+=4;
  36. tempBuffer.writeUInt32LE(this.headerInfoSize,this.pos);this.pos+=4;
  37. tempBuffer.writeUInt32LE(this.width,this.pos);this.pos+=4;
  38. tempBuffer.writeInt32LE(-this.height,this.pos);this.pos+=4;
  39. tempBuffer.writeUInt16LE(this.planes,this.pos);this.pos+=2;
  40. tempBuffer.writeUInt16LE(this.bitPP,this.pos);this.pos+=2;
  41. tempBuffer.writeUInt32LE(this.compress,this.pos);this.pos+=4;
  42. tempBuffer.writeUInt32LE(this.rgbSize,this.pos);this.pos+=4;
  43. tempBuffer.writeUInt32LE(this.hr,this.pos);this.pos+=4;
  44. tempBuffer.writeUInt32LE(this.vr,this.pos);this.pos+=4;
  45. tempBuffer.writeUInt32LE(this.colors,this.pos);this.pos+=4;
  46. tempBuffer.writeUInt32LE(this.importantColors,this.pos);this.pos+=4;
  47. var i=0;
  48. var rowBytes = 3*this.width+this.extraBytes;
  49. for (var y = 0; y <this.height; y++){
  50. for (var x = 0; x < this.width; x++){
  51. var p = this.pos+y*rowBytes+x*3;
  52. i++;//a
  53. tempBuffer[p]= this.buffer[i++];//b
  54. tempBuffer[p+1] = this.buffer[i++];//g
  55. tempBuffer[p+2] = this.buffer[i++];//r
  56. }
  57. if(this.extraBytes>0){
  58. var fillOffset = this.pos+y*rowBytes+this.width*3;
  59. tempBuffer.fill(0,fillOffset,fillOffset+this.extraBytes);
  60. }
  61. }
  62. return tempBuffer;
  63. };
  64. module.exports = function(imgData, quality) {
  65. if (typeof quality === 'undefined') quality = 100;
  66. var encoder = new BmpEncoder(imgData);
  67. var data = encoder.encode();
  68. return {
  69. data: data,
  70. width: imgData.width,
  71. height: imgData.height
  72. };
  73. };