util.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const formatTime = date => {
  2. const year = date.getFullYear()
  3. const month = date.getMonth() + 1
  4. const day = date.getDate()
  5. const hour = date.getHours()
  6. const minute = date.getMinutes()
  7. const second = date.getSeconds()
  8. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  9. }
  10. const formatNumber = n => {
  11. n = n.toString()
  12. return n[1] ? n : '0' + n
  13. }
  14. //4合1
  15. function convert4to1(res) {
  16. let arr = [];
  17. for (let i = 0; i < res.length; i++) {
  18. if (i % 4 == 0) {
  19. let rule = 0.29900 * res[i] + 0.58700 * res[i + 1] + 0.11400 * res[i + 2];
  20. if (rule > 200) {
  21. res[i] = 0;
  22. } else {
  23. res[i] = 1;
  24. }
  25. arr.push(res[i]);
  26. }
  27. }
  28. return arr;
  29. }
  30. //8合1
  31. function convert8to1(arr) {
  32. let data = [];
  33. for (let k = 0; k < arr.length; k += 8) {
  34. let temp = arr[k] * 128 + arr[k + 1] * 64 + arr[k + 2] * 32 + arr[k + 3] * 16 + arr[k + 4] * 8 + arr[k + 5] * 4 +
  35. arr[k + 6] * 2 + arr[k + 7] * 1
  36. data.push(temp);
  37. }
  38. return data;
  39. }
  40. //我的图片宽度是240,那么拼接的指令就是[29, 118, 48, 0, 30, 0, 240, 0]
  41. //我的图片宽度是160,那么拼接的指令就是[29, 118, 48, 0, 20, 0, 160, 0]
  42. //补充一点,打印非二维码的图片,宽度一定要是24的倍数,不然打印也会出现乱码
  43. function toArrayBuffer(res) {
  44. let arr = convert4to1(res);
  45. let data = convert8to1(arr);
  46. let cmds = [].concat([27, 97, 1], [29, 118, 48, 0, 30, 0, 240, 0], data, [27, 74, 3], [27, 64]);
  47. return new Uint8Array(cmds).buffer;
  48. }
  49. function zip_image(res) {
  50. let arr = convert4to1(res.data);
  51. let data = convert8to1(arr);
  52. return data;
  53. }
  54. module.exports = {
  55. formatTime: formatTime,
  56. toArrayBuffer: toArrayBuffer,
  57. zip_image: zip_image,
  58. }