将ImageData转换为B&W并通过蓝牙热敏打印机进行打印

时间:2019-10-07 17:57:40

标签: javascript bluetooth thermal-printer

我目前正在尝试通过网络蓝牙将图像打印到蓝牙打印机上。 webBluetooth's github中的示例不适用于我。

let image = document.querySelector('#image');
    // Use the canvas to get image data
    let canvas = document.createElement('canvas');
    // Canvas dimensions need to be a multiple of 40 for this printer
    canvas.width = 120;
    canvas.height = 120;
    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    let imageData = context.getImageData(0, 0, canvas.width, canvas.height).data;

    function getDarkPixel(x, y) {
      // Return the pixels that will be printed black
      let red = imageData[((canvas.width * y) + x) * 4];
      let green = imageData[((canvas.width * y) + x) * 4 + 1];
      let blue = imageData[((canvas.width * y) + x) * 4 + 2];
      return (red + green + blue) > 0 ? 1 : 0;
    }

    function getImagePrintData() {
      if (imageData == null) {
        console.log('No image to print!');
        return new Uint8Array([]);
      }
      // Each 8 pixels in a row is represented by a byte
      let printData = new Uint8Array(canvas.width / 8 * canvas.height + 8);
      let offset = 0;
      // Set the header bytes for printing the image
      printData[0] = 29;  // Print raster bitmap
      printData[1] = 118; // Print raster bitmap
      printData[2] = 48; // Print raster bitmap
      printData[3] = 0;  // Normal 203.2 DPI
      printData[4] = canvas.width / 8; // Number of horizontal data bits (LSB)
      printData[5] = 0; // Number of horizontal data bits (MSB)
      printData[6] = canvas.height % 256; // Number of vertical data bits (LSB)
      printData[7] = canvas.height / 256;  // Number of vertical data bits (MSB)
      offset = 7;
      // Loop through image rows in bytes
      for (let i = 0; i < canvas.height; ++i) {
        for (let k = 0; k < canvas.width / 8; ++k) {
          let k8 = k * 8;
          //  Pixel to bit position mapping
          printData[++offset] = getDarkPixel(k8 + 0, i) * 128 + getDarkPixel(k8 + 1, i) * 64 +
                      getDarkPixel(k8 + 2, i) * 32 + getDarkPixel(k8 + 3, i) * 16 +
                      getDarkPixel(k8 + 4, i) * 8 + getDarkPixel(k8 + 5, i) * 4 +
                      getDarkPixel(k8 + 6, i) * 2 + getDarkPixel(k8 + 7, i);
        }
      }
      return printData;
    }

请注意,我已经可以通过webBluetooth打印文本。我可以从Bluetooth Mate应用程序打印文本和图像。但是我想通过webBluetooth打印图像。

有人知道怎么做吗?我的打印机是MTP-II(goojprt PT-210)。

0 个答案:

没有答案