Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Printing image in Thermal printer
QtWS25 Last Chance

Printing image in Thermal printer

Scheduled Pinned Locked Moved Solved General and Desktop
8 Posts 3 Posters 1.5k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    Ramkumar Mohan
    wrote on 2 Sept 2023, 11:21 last edited by Ramkumar Mohan
    #1

    I wrote the below code , i want to print black&white image in Thermal Printer model :RP203-RS232-TTL .

    if i give p->printimage (img); only junk characters is printed..

    Printer.CPP

    /*****************************************************************
    * Thermal Printer Interface Library based on QT for the Rasp-Pi
    * Based on the Arduino Library from Adafruit
    * using QExtSerialPort
    * Autor: Tobias Floery
    * E-Mail: tobias@floery.net
    ***************************************************************/
    
          #include "printer.h"
          #include <QImage>
          #include <iostream>
          #include <unistd.h>
    
          Printer::Printer(QObject *parent) :
          QObject(parent)
          {
          }
    
          // opens the serial port specified py path
    
          bool Printer::open(QString path) {
    
          port = new QextSerialPort(path);
    
          if (!port->open(QIODevice::WriteOnly))
              return false;
          // set options
          port->setBaudRate(BAUD9600);
          port->setDataBits(DATA_8);
          port->setFlowControl(FLOW_OFF);
          port->setParity(PAR_NONE);
    
          usleep(10000);
             return true;
          }
    
              // close the serial port
          void Printer::close() {
          port->close();
          }
    
           // write single byte
          void Printer::write(quint8 byte) {
          port->write((const char*)&byte, 1);
          }
    
            / / write a string
          void Printer::write(QString str)
          {
          port->write(str.toUtf8());
         }
    
           void Printer::writes(char SOMETHING)
          {
           port->write(&SOMETHING);
          }
    
    
          // initialize the printer
          void Printer::init() {
              reset();
              setStatus(true);
              setControlParameter();
              setPrintDensity();
              setSleepTime();
              setCodeTable();
              setCharacterSet();
              setBarcodePrintReadable();
          }
    
          // reset the printer
          void Printer::reset() {
              write(27);
              write(64);
              usleep(50000);
          }
    
          // sets the printer online (true) or ofline (false)
          void Printer::setStatus(bool state) {
              write(27);
              write(61);
              write(state);
          }
    
          // set control parameters: heatingDots, heatingTime, heatingInterval
          void Printer::setControlParameter(quint8 heatingDots, quint8 heatingTime, quint8             heatingInterval) {
              write(27);
              write(55);
              write(heatingDots);
              write(heatingTime);
              write(heatingInterval);
          }
    
          // set sleep Time in seconds, time after last print the printer should stay awake
          void Printer::setSleepTime(quint8 seconds) {
              write(27);
              write(56);
              write(seconds);
              usleep(50000);
              write(0xFF);
          }
    
          // set double width mode: on=true, off=false
          void Printer::setDoubleWidth(bool state) {
              write(27);
              write(state?14:20);
    
          }
    
    
          // set the print density and break time
          void Printer::setPrintDensity(quint8 printDensity, quint8 printBreakTime) {
              write(18);
              write(35);
              write((printBreakTime << 5) | printDensity);
          }
    
          // set the used character set
          void Printer::setCharacterSet(CharacterSet set) {
              write(27);
              write(82);
              write(set);
          }
    
          / / set the used code table
          void Printer::setCodeTable(CodeTable table) {
              write(27);
              write(116);
              write(table);
          }
    
          // feed single line
          void Printer::feed(void) {
              write(10);
          }
    
          // feed <<lines>> lines
          void Printer::feed(quint8 lines) {
              write(27);
              write(74);
              write(lines);
          }
    
          // set line spacing
          void Printer::setLineSpacing(quint8 spacing) {
              write(27);
              write(51);
              write(spacing);
          }
    
          // set Align Mode: LEFT, MIDDLE, RIGHT
          void Printer::setAlign(AlignMode align) {
              write(27);
              write(97);
              write(align);
          }
    
          // set how many blanks should be kept on the left side
          void Printer::setLeftBlankCharNums(quint8 space) {
              if (space >= 47) space = 47;
    
              write(27);
              write(66);
              write(space);
          }
    
          // set Bold Mode: on=true, off=false
          void Printer::setBold(bool state) {
              write(27);
              write(32);
              write((quint8) state);
              write(27);
              write(69);
              write((quint8) state);
          }
    
          // set Reverse printing Mode
          void Printer::setReverse(bool state) {
              write(29);
              write(66);
              write((quint8) state);
          }
    
          // set Up/Down Mode
          void Printer::setUpDown(bool state) {
              write(27);
              write(123);
              write((quint8) state);
          }
    
          // set Underline printing
          void Printer::setUnderline(bool state) {
              write(27);
              write(45);
              write((quint8) state);
          }
    
          // enable / disable the key on the frontpanel
          void Printer::setKeyPanel(bool state) {
              write(27);
              write(99);
              write(53);
              write((quint8) state);
          }
    
           // where should a readable barcode code be printed
          void Printer::setBarcodePrintReadable(PrintReadable n) {
              write(29);
              write(72);
              write(n);
          }
    
          // sets the height of the barcode in pixels
          void Printer::setBarcodeHeight(quint8 height) {
              if (height <= 1) height = 1;
    
              write(29);
              write(104);
              write(height);
          }
    
          // sets the barcode line widths (only 2 or 3)
          void Printer::setBarCodeWidth(quint8 width) {
              if (width <= 2) width=2;
              else if (width >= 3) width=3;
    
              write(29);
              write(119);
              write(width);
          }
    
          // prints a barcode
          void Printer::printBarcode(QString data, BarcodeType type) {
              write(29);
              write(107);
              write(type);
              write(data);
              write(0);
          }
    
                // print Image, threshold defines grayscale to black&withe threshold level
          void Printer::printImage(QImage img) {
              int width = img.width() / 8;
              int height = img.height();
              quint8 data[width * height];
              memset(data, 0, width * height);
    
              // QImage::bits seemed to return ARGB values
              for (int y = 0; y < img.height(); y++) {
                  for (int x = 0; x < img.width(); x++) {
                     quint8 pixel = img.pixelIndex(x, y);
                      data[y * width + x / 8] += (pixel & 0x01) << (7 - x % 8);
                  }
              }
    
              // Split images with height > 255 into parts (from Adafruit)
              for (int rowStart = 0; rowStart < height; rowStart += 255) {
                  int chunkHeight = ((height - rowStart) > 255) ? 255 : (height - rowStart);
                  write(18);
                  write(42);
                  write(chunkHeight);
                  write(width);
    
                  for (int i = 0; i < (width * chunkHeight); i++) {
                      write(data[rowStart * width + i]);
                  }
                  usleep(50000);
              }
          }
    
    
    

    MainWindow.CPP

    
          #include "mainwindow.h"
          #include "ui_mainwindow.h"
          #include <QImage>
          #include <iostream>
          #include "printer.h"
          #include <QDebug>
          #include <unistd.h>
          MainWindow::MainWindow(QWidget *parent) :
              QMainWindow(parent),
              ui(new Ui::MainWindow)
          {
              ui->setupUi(this);
          }
    
          MainWindow::~MainWindow()
          {
              delete ui;
          }
    
          int MainWindow::on_pushButton_clicked()
          {
              Printer *p = new Printer();
              std::cout << "Trying to open port" << std::endl;
              bool res = p->open("/dev/ttyS0");
              std::cout << "Status: " << res << std::endl;
              if (!res) {
                  std::cerr << "Error opening port, aborting" << std::endl;
                  return (0);
              }
              p->init();
              p->feed();
              p->printBarcode("Welcome");
              QImage img("/home/pi/git/build-Image_Print-Desktop-Debug/bw_image.png");
              img = img.convertToFormat(QImage::Format_Mono);
              p->printImage(img);
              p->feed();
              p->close();
              return 0;
          }
    

    the junk data.. below,

    WhatsApp Image 2023-09-02 at 4.50.18 PM.jpeg

    how to print the image ,
    Thanks in advance

    JonBJ 1 Reply Last reply 2 Sept 2023, 11:36
    0
    • SGaistS SGaist
      27 Sept 2023, 19:05

      Is it me or does it seems that your image is printed in "the wrong direction". It looks like you have things mirrored but per column.

      R Offline
      R Offline
      Ramkumar Mohan
      wrote on 28 Sept 2023, 07:36 last edited by
      #7
      This post is deleted!
      1 Reply Last reply
      0
      • R Ramkumar Mohan
        2 Sept 2023, 11:21

        I wrote the below code , i want to print black&white image in Thermal Printer model :RP203-RS232-TTL .

        if i give p->printimage (img); only junk characters is printed..

        Printer.CPP

        /*****************************************************************
        * Thermal Printer Interface Library based on QT for the Rasp-Pi
        * Based on the Arduino Library from Adafruit
        * using QExtSerialPort
        * Autor: Tobias Floery
        * E-Mail: tobias@floery.net
        ***************************************************************/
        
              #include "printer.h"
              #include <QImage>
              #include <iostream>
              #include <unistd.h>
        
              Printer::Printer(QObject *parent) :
              QObject(parent)
              {
              }
        
              // opens the serial port specified py path
        
              bool Printer::open(QString path) {
        
              port = new QextSerialPort(path);
        
              if (!port->open(QIODevice::WriteOnly))
                  return false;
              // set options
              port->setBaudRate(BAUD9600);
              port->setDataBits(DATA_8);
              port->setFlowControl(FLOW_OFF);
              port->setParity(PAR_NONE);
        
              usleep(10000);
                 return true;
              }
        
                  // close the serial port
              void Printer::close() {
              port->close();
              }
        
               // write single byte
              void Printer::write(quint8 byte) {
              port->write((const char*)&byte, 1);
              }
        
                / / write a string
              void Printer::write(QString str)
              {
              port->write(str.toUtf8());
             }
        
               void Printer::writes(char SOMETHING)
              {
               port->write(&SOMETHING);
              }
        
        
              // initialize the printer
              void Printer::init() {
                  reset();
                  setStatus(true);
                  setControlParameter();
                  setPrintDensity();
                  setSleepTime();
                  setCodeTable();
                  setCharacterSet();
                  setBarcodePrintReadable();
              }
        
              // reset the printer
              void Printer::reset() {
                  write(27);
                  write(64);
                  usleep(50000);
              }
        
              // sets the printer online (true) or ofline (false)
              void Printer::setStatus(bool state) {
                  write(27);
                  write(61);
                  write(state);
              }
        
              // set control parameters: heatingDots, heatingTime, heatingInterval
              void Printer::setControlParameter(quint8 heatingDots, quint8 heatingTime, quint8             heatingInterval) {
                  write(27);
                  write(55);
                  write(heatingDots);
                  write(heatingTime);
                  write(heatingInterval);
              }
        
              // set sleep Time in seconds, time after last print the printer should stay awake
              void Printer::setSleepTime(quint8 seconds) {
                  write(27);
                  write(56);
                  write(seconds);
                  usleep(50000);
                  write(0xFF);
              }
        
              // set double width mode: on=true, off=false
              void Printer::setDoubleWidth(bool state) {
                  write(27);
                  write(state?14:20);
        
              }
        
        
              // set the print density and break time
              void Printer::setPrintDensity(quint8 printDensity, quint8 printBreakTime) {
                  write(18);
                  write(35);
                  write((printBreakTime << 5) | printDensity);
              }
        
              // set the used character set
              void Printer::setCharacterSet(CharacterSet set) {
                  write(27);
                  write(82);
                  write(set);
              }
        
              / / set the used code table
              void Printer::setCodeTable(CodeTable table) {
                  write(27);
                  write(116);
                  write(table);
              }
        
              // feed single line
              void Printer::feed(void) {
                  write(10);
              }
        
              // feed <<lines>> lines
              void Printer::feed(quint8 lines) {
                  write(27);
                  write(74);
                  write(lines);
              }
        
              // set line spacing
              void Printer::setLineSpacing(quint8 spacing) {
                  write(27);
                  write(51);
                  write(spacing);
              }
        
              // set Align Mode: LEFT, MIDDLE, RIGHT
              void Printer::setAlign(AlignMode align) {
                  write(27);
                  write(97);
                  write(align);
              }
        
              // set how many blanks should be kept on the left side
              void Printer::setLeftBlankCharNums(quint8 space) {
                  if (space >= 47) space = 47;
        
                  write(27);
                  write(66);
                  write(space);
              }
        
              // set Bold Mode: on=true, off=false
              void Printer::setBold(bool state) {
                  write(27);
                  write(32);
                  write((quint8) state);
                  write(27);
                  write(69);
                  write((quint8) state);
              }
        
              // set Reverse printing Mode
              void Printer::setReverse(bool state) {
                  write(29);
                  write(66);
                  write((quint8) state);
              }
        
              // set Up/Down Mode
              void Printer::setUpDown(bool state) {
                  write(27);
                  write(123);
                  write((quint8) state);
              }
        
              // set Underline printing
              void Printer::setUnderline(bool state) {
                  write(27);
                  write(45);
                  write((quint8) state);
              }
        
              // enable / disable the key on the frontpanel
              void Printer::setKeyPanel(bool state) {
                  write(27);
                  write(99);
                  write(53);
                  write((quint8) state);
              }
        
               // where should a readable barcode code be printed
              void Printer::setBarcodePrintReadable(PrintReadable n) {
                  write(29);
                  write(72);
                  write(n);
              }
        
              // sets the height of the barcode in pixels
              void Printer::setBarcodeHeight(quint8 height) {
                  if (height <= 1) height = 1;
        
                  write(29);
                  write(104);
                  write(height);
              }
        
              // sets the barcode line widths (only 2 or 3)
              void Printer::setBarCodeWidth(quint8 width) {
                  if (width <= 2) width=2;
                  else if (width >= 3) width=3;
        
                  write(29);
                  write(119);
                  write(width);
              }
        
              // prints a barcode
              void Printer::printBarcode(QString data, BarcodeType type) {
                  write(29);
                  write(107);
                  write(type);
                  write(data);
                  write(0);
              }
        
                    // print Image, threshold defines grayscale to black&withe threshold level
              void Printer::printImage(QImage img) {
                  int width = img.width() / 8;
                  int height = img.height();
                  quint8 data[width * height];
                  memset(data, 0, width * height);
        
                  // QImage::bits seemed to return ARGB values
                  for (int y = 0; y < img.height(); y++) {
                      for (int x = 0; x < img.width(); x++) {
                         quint8 pixel = img.pixelIndex(x, y);
                          data[y * width + x / 8] += (pixel & 0x01) << (7 - x % 8);
                      }
                  }
        
                  // Split images with height > 255 into parts (from Adafruit)
                  for (int rowStart = 0; rowStart < height; rowStart += 255) {
                      int chunkHeight = ((height - rowStart) > 255) ? 255 : (height - rowStart);
                      write(18);
                      write(42);
                      write(chunkHeight);
                      write(width);
        
                      for (int i = 0; i < (width * chunkHeight); i++) {
                          write(data[rowStart * width + i]);
                      }
                      usleep(50000);
                  }
              }
        
        
        

        MainWindow.CPP

        
              #include "mainwindow.h"
              #include "ui_mainwindow.h"
              #include <QImage>
              #include <iostream>
              #include "printer.h"
              #include <QDebug>
              #include <unistd.h>
              MainWindow::MainWindow(QWidget *parent) :
                  QMainWindow(parent),
                  ui(new Ui::MainWindow)
              {
                  ui->setupUi(this);
              }
        
              MainWindow::~MainWindow()
              {
                  delete ui;
              }
        
              int MainWindow::on_pushButton_clicked()
              {
                  Printer *p = new Printer();
                  std::cout << "Trying to open port" << std::endl;
                  bool res = p->open("/dev/ttyS0");
                  std::cout << "Status: " << res << std::endl;
                  if (!res) {
                      std::cerr << "Error opening port, aborting" << std::endl;
                      return (0);
                  }
                  p->init();
                  p->feed();
                  p->printBarcode("Welcome");
                  QImage img("/home/pi/git/build-Image_Print-Desktop-Debug/bw_image.png");
                  img = img.convertToFormat(QImage::Format_Mono);
                  p->printImage(img);
                  p->feed();
                  p->close();
                  return 0;
              }
        

        the junk data.. below,

        WhatsApp Image 2023-09-02 at 4.50.18 PM.jpeg

        how to print the image ,
        Thanks in advance

        JonBJ Offline
        JonBJ Offline
        JonB
        wrote on 2 Sept 2023, 11:36 last edited by JonB 9 Feb 2023, 11:37
        #2

        @Ramkumar-Mohan You have been here for a while, please use Code (</> icon) tags around the blobs you paste.

        R 1 Reply Last reply 2 Sept 2023, 12:23
        0
        • JonBJ JonB
          2 Sept 2023, 11:36

          @Ramkumar-Mohan You have been here for a while, please use Code (</> icon) tags around the blobs you paste.

          R Offline
          R Offline
          Ramkumar Mohan
          wrote on 2 Sept 2023, 12:23 last edited by Ramkumar Mohan 9 Feb 2023, 12:31
          #3

          @JonB ok, kindly give me any suggestions.

          SGaistS 1 Reply Last reply 2 Sept 2023, 19:30
          0
          • R Ramkumar Mohan
            2 Sept 2023, 12:23

            @JonB ok, kindly give me any suggestions.

            SGaistS Offline
            SGaistS Offline
            SGaist
            Lifetime Qt Champion
            wrote on 2 Sept 2023, 19:30 last edited by
            #4

            Hi,

            Before printing the content of a QImage, start by printing a hardcoded image to ensure your transmission code is properly working.

            Next, ensure the QImage has a fomat that is compatible with your printer. If not, convert it first.

            Interested in AI ? www.idiap.ch
            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

            R 1 Reply Last reply 27 Sept 2023, 10:53
            1
            • SGaistS SGaist
              2 Sept 2023, 19:30

              Hi,

              Before printing the content of a QImage, start by printing a hardcoded image to ensure your transmission code is properly working.

              Next, ensure the QImage has a fomat that is compatible with your printer. If not, convert it first.

              R Offline
              R Offline
              Ramkumar Mohan
              wrote on 27 Sept 2023, 10:53 last edited by Ramkumar Mohan
              #5

              @SGaist

              I have printed the image in the thermal printer, but it does not print as clearly.
              let me know, if you know how.
              thanks,

              Printer.CPP

              #include "printer.h"
              #include <QImage>
              #include <iostream>
              #include <unistd.h>
              #include <QDebug>
              #include <QPixmap>
              Printer::Printer(QObject *parent) :
                  QObject(parent)
              {
              }
              
              // opens the serial port specified py path
              
              bool Printer::open(QString path) {
              
                  port = new QextSerialPort(path);
              
                  if (!port->open(QIODevice::WriteOnly))
                      return false;
                  // set options
                  port->setBaudRate(BAUD9600);
                  port->setDataBits(DATA_8);
                  port->setFlowControl(FLOW_OFF);
                  port->setParity(PAR_NONE);
              
                  usleep(10000);
                  return true;
              }
              
              // close the serial port
              void Printer::close() {
                  port->close();
              }
              
              // write single byte
              void Printer::write(quint8 byte) {
                  port->write((const char*)&byte, 1);
              }
              
              // write a string
              void Printer::write(QString str)
              {
                  port->write(str.toUtf8());
              }
              
              // initialize the printer
              void Printer::init() {
                  reset();
                  setStatus(true);
                  setControlParameter();
                  setPrintDensity();
                  setSleepTime();
                  setCodeTable();
                  setCharacterSet();
                  setBarcodePrintReadable();
              }
              
              // reset the printer
              void Printer::reset() {
                  write(27);
                  write(64);
                  usleep(50000);
              }
              
              // set control parameters: heatingDots, heatingTime, heatingInterval
              void Printer::setControlParameter(quint8 heatingDots, quint8 heatingTime, quint8 heatingInterval) {
                  write(27);
                  write(55);
                  write(heatingDots);
                  write(heatingTime);
                  write(heatingInterval);
              }
              
              // set sleep Time in seconds, time after last print the printer should stay awake
              void Printer::setSleepTime(quint8 seconds) {
                  write(27);
                  write(56);
                  write(seconds);
                  usleep(50000);
                  write(0xFF);
              }
              
              // set double width mode: on=true, off=false
              void Printer::setDoubleWidth(bool state) {
                  write(27);
                  write(state?14:20);
              
              }
              
              
              // set the print density and break time
              void Printer::setPrintDensity(quint8 printDensity, quint8 printBreakTime) {
                  write(18);
                  write(35);
                  write((printBreakTime << 5) | printDensity);
              }
              
              // set the used character set
              void Printer::setCharacterSet(CharacterSet set) {
                  write(27);
                  write(82);
                  write(set);
              }
              
              // set the used code table
              void Printer::setCodeTable(CodeTable table) {
                  write(27);
                  write(116);
                  write(table);
              }
              
              // feed single line
              void Printer::feed(void) {
                  write(10);
              }
              
              // feed <<lines>> lines
              void Printer::feed(quint8 lines) {
                  write(27);
                  write(74);
                  write(lines);
              }
              
              // set line spacing
              void Printer::setLineSpacing(quint8 spacing) {
                  write(27);
                  write(51);
                  write(spacing);
              }
              
              // enable / disable the key on the frontpanel
              void Printer::setKeyPanel(bool state) {
                  write(27);
                  write(99);
                  write(53);
                  write((quint8) state);
              }
              
              // where should a readable barcode code be printed
              void Printer::setBarcodePrintReadable(PrintReadable n) {
                  write(29);
                  write(72);
                  write(n);
              }
              
              // sets the height of the barcode in pixels
              void Printer::setBarcodeHeight(quint8 height) {
                  if (height <= 1) height = 1;
              
                  write(29);
                  write(104);
                  write(height);
              }
              
              // sets the barcode line widths (only 2 or 3)
              void Printer::setBarCodeWidth(quint8 width) {
                  if (width <= 2) width=2;
                  else if (width >= 3) width=3;
              
                  write(29);
                  write(119);
                  write(width);
              }
              
              // prints a barcode
              void Printer::printBarcode(QString data, BarcodeType type) {
                  write(29);
                  write(107);
                  write(type);
                  write(data);
                  write(0);
              }
              
              
              bool Printer::isPrinterReady()
              {
                  return port->isOpen() && port->isWritable();
              }
              
              void Printer::printImage(const QImage &image)
              {
                  if (!isPrinterReady())
                  {
                      qDebug() << "Printer is not ready.";
                      return;
                  }
                  qreal scaleFactor = 3.0; // Increase DPI by a factor of 2
                        qreal darknessFactor = 1.8; // Adjust darkness level (experiment with this value)
                        QImage highDpiImage = image.scaled(image.width() * scaleFactor, image.height() * scaleFactor, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
              
                  // Convert the QImage to a monochrome (1-bit) image
                  QImage monochromeImage = image.convertToFormat(QImage::Format_Mono);
              
                  // Calculate the width of the image in bytes
                  int bytesPerLine = (monochromeImage.width() + 7) / 8;
              
                  // Send the ESC/POS command to print the image
                  QByteArray printCommand;
                  printCommand.append(char(0x1D));  // ESC
                  printCommand.append(char(0x76));  // 'v'
                  printCommand.append(char(0x30));  // '0'
                  printCommand.append(char(0x00));  // Mode (0 for normal)
              
                  // Append the image width and height
                  printCommand.append(char(bytesPerLine & 0xFF));
                  printCommand.append(char((bytesPerLine >> 8) & 0xFF));
                  printCommand.append(char(monochromeImage.height() & 0xFF));
                  printCommand.append(char((monochromeImage.height() >> 8) & 0xFF));
              
                  // Send the print command
                  port->write(printCommand);
              
                  // Send the image data
                  QByteArray imageData;
                  for (int y = 0; y < monochromeImage.height(); ++y)
                  {
                      for (int x = 0; x < bytesPerLine; ++x)
                      {
                          uchar byte = 0;
                          for (int bit = 0; bit < 8; ++bit)
                          {
                              int pixelX = x * 8 + bit;
                              if (pixelX < monochromeImage.width())
                              {
                                  bool isBlackPixel = monochromeImage.pixel(pixelX, y) == qRgb(0, 0, 0);
                                  byte |= (isBlackPixel ? 0x01 : 0x00) << bit;
                              }
                          }
                          byte *= darknessFactor; // Adjust this factor for darkness level
              
                          imageData.append(byte);
                      }
                  }
              
                  // Send the image data
                  port->write(imageData);
                  write("\n"); // Print a newline to advance to the next line
              }
              
              

              MainWindow.CPP

              #include "mainwindow.h"
              #include "ui_mainwindow.h"
              #include <QImage>
              #include <iostream>
              #include "printer.h"
              #include <QDebug>
              #include <unistd.h>
              #include <QPainter>
              #include <QBuffer>
              #include <QPainter>
              MainWindow::MainWindow(QWidget *parent) :
                  QMainWindow(parent),
                  ui(new Ui::MainWindow)
              {
                  ui->setupUi(this);
                  
              }
              
              MainWindow::~MainWindow()
              {
                  delete ui;
              }
              
              QImage MainWindow::loadImage(const QString &filePath)
              {
                  QImage image(filePath);
                  if (image.isNull())
                  {
                      qDebug() << "Error loading image: " << filePath;
                  }
                  return image;
              }
              
              void MainWindow::on_pushButton_clicked()
              {
                  QApplication::processEvents();
              
                  Printer *printer = new Printer();
                  std::cout << "Trying to open port..." << std::endl;
                  bool res = printer->open("/dev/ttyS0");
                  std::cout << "Status: " << res << std::endl;
                  if (!res)
                  {
                      std::cerr << "Error opening port, aborting" << std::endl;
                      return;
                  }
                  QString imagePath = "/home/pi/git/Image_Print/Raspi.png"; // Replace with the path to your image
              
                  QImage image = loadImage(imagePath);
              
                  if (!image.isNull())
                  {
                      qDebug()<<"Image enter";
              
                      printer->write("Data");
                      printer->feed();
                      printer->feed();
                      printer->printImage(image);
                      printer->feed();
                      printer->feed();
              
                  }
                  else
                  {
                      qDebug() << "Image is null or invalid.";
                  }
              
                  printer->close();
              }
              
              

              Output:-

              Printed Image is below:-

              WhatsApp Image 2023-09-27 at 4.33.48 PM.jpeg

              Original Image is below:-

              Raspberry_Pi-Logo.wine.jpg

              SGaistS 1 Reply Last reply 27 Sept 2023, 19:05
              0
              • R Ramkumar Mohan
                27 Sept 2023, 10:53

                @SGaist

                I have printed the image in the thermal printer, but it does not print as clearly.
                let me know, if you know how.
                thanks,

                Printer.CPP

                #include "printer.h"
                #include <QImage>
                #include <iostream>
                #include <unistd.h>
                #include <QDebug>
                #include <QPixmap>
                Printer::Printer(QObject *parent) :
                    QObject(parent)
                {
                }
                
                // opens the serial port specified py path
                
                bool Printer::open(QString path) {
                
                    port = new QextSerialPort(path);
                
                    if (!port->open(QIODevice::WriteOnly))
                        return false;
                    // set options
                    port->setBaudRate(BAUD9600);
                    port->setDataBits(DATA_8);
                    port->setFlowControl(FLOW_OFF);
                    port->setParity(PAR_NONE);
                
                    usleep(10000);
                    return true;
                }
                
                // close the serial port
                void Printer::close() {
                    port->close();
                }
                
                // write single byte
                void Printer::write(quint8 byte) {
                    port->write((const char*)&byte, 1);
                }
                
                // write a string
                void Printer::write(QString str)
                {
                    port->write(str.toUtf8());
                }
                
                // initialize the printer
                void Printer::init() {
                    reset();
                    setStatus(true);
                    setControlParameter();
                    setPrintDensity();
                    setSleepTime();
                    setCodeTable();
                    setCharacterSet();
                    setBarcodePrintReadable();
                }
                
                // reset the printer
                void Printer::reset() {
                    write(27);
                    write(64);
                    usleep(50000);
                }
                
                // set control parameters: heatingDots, heatingTime, heatingInterval
                void Printer::setControlParameter(quint8 heatingDots, quint8 heatingTime, quint8 heatingInterval) {
                    write(27);
                    write(55);
                    write(heatingDots);
                    write(heatingTime);
                    write(heatingInterval);
                }
                
                // set sleep Time in seconds, time after last print the printer should stay awake
                void Printer::setSleepTime(quint8 seconds) {
                    write(27);
                    write(56);
                    write(seconds);
                    usleep(50000);
                    write(0xFF);
                }
                
                // set double width mode: on=true, off=false
                void Printer::setDoubleWidth(bool state) {
                    write(27);
                    write(state?14:20);
                
                }
                
                
                // set the print density and break time
                void Printer::setPrintDensity(quint8 printDensity, quint8 printBreakTime) {
                    write(18);
                    write(35);
                    write((printBreakTime << 5) | printDensity);
                }
                
                // set the used character set
                void Printer::setCharacterSet(CharacterSet set) {
                    write(27);
                    write(82);
                    write(set);
                }
                
                // set the used code table
                void Printer::setCodeTable(CodeTable table) {
                    write(27);
                    write(116);
                    write(table);
                }
                
                // feed single line
                void Printer::feed(void) {
                    write(10);
                }
                
                // feed <<lines>> lines
                void Printer::feed(quint8 lines) {
                    write(27);
                    write(74);
                    write(lines);
                }
                
                // set line spacing
                void Printer::setLineSpacing(quint8 spacing) {
                    write(27);
                    write(51);
                    write(spacing);
                }
                
                // enable / disable the key on the frontpanel
                void Printer::setKeyPanel(bool state) {
                    write(27);
                    write(99);
                    write(53);
                    write((quint8) state);
                }
                
                // where should a readable barcode code be printed
                void Printer::setBarcodePrintReadable(PrintReadable n) {
                    write(29);
                    write(72);
                    write(n);
                }
                
                // sets the height of the barcode in pixels
                void Printer::setBarcodeHeight(quint8 height) {
                    if (height <= 1) height = 1;
                
                    write(29);
                    write(104);
                    write(height);
                }
                
                // sets the barcode line widths (only 2 or 3)
                void Printer::setBarCodeWidth(quint8 width) {
                    if (width <= 2) width=2;
                    else if (width >= 3) width=3;
                
                    write(29);
                    write(119);
                    write(width);
                }
                
                // prints a barcode
                void Printer::printBarcode(QString data, BarcodeType type) {
                    write(29);
                    write(107);
                    write(type);
                    write(data);
                    write(0);
                }
                
                
                bool Printer::isPrinterReady()
                {
                    return port->isOpen() && port->isWritable();
                }
                
                void Printer::printImage(const QImage &image)
                {
                    if (!isPrinterReady())
                    {
                        qDebug() << "Printer is not ready.";
                        return;
                    }
                    qreal scaleFactor = 3.0; // Increase DPI by a factor of 2
                          qreal darknessFactor = 1.8; // Adjust darkness level (experiment with this value)
                          QImage highDpiImage = image.scaled(image.width() * scaleFactor, image.height() * scaleFactor, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                
                    // Convert the QImage to a monochrome (1-bit) image
                    QImage monochromeImage = image.convertToFormat(QImage::Format_Mono);
                
                    // Calculate the width of the image in bytes
                    int bytesPerLine = (monochromeImage.width() + 7) / 8;
                
                    // Send the ESC/POS command to print the image
                    QByteArray printCommand;
                    printCommand.append(char(0x1D));  // ESC
                    printCommand.append(char(0x76));  // 'v'
                    printCommand.append(char(0x30));  // '0'
                    printCommand.append(char(0x00));  // Mode (0 for normal)
                
                    // Append the image width and height
                    printCommand.append(char(bytesPerLine & 0xFF));
                    printCommand.append(char((bytesPerLine >> 8) & 0xFF));
                    printCommand.append(char(monochromeImage.height() & 0xFF));
                    printCommand.append(char((monochromeImage.height() >> 8) & 0xFF));
                
                    // Send the print command
                    port->write(printCommand);
                
                    // Send the image data
                    QByteArray imageData;
                    for (int y = 0; y < monochromeImage.height(); ++y)
                    {
                        for (int x = 0; x < bytesPerLine; ++x)
                        {
                            uchar byte = 0;
                            for (int bit = 0; bit < 8; ++bit)
                            {
                                int pixelX = x * 8 + bit;
                                if (pixelX < monochromeImage.width())
                                {
                                    bool isBlackPixel = monochromeImage.pixel(pixelX, y) == qRgb(0, 0, 0);
                                    byte |= (isBlackPixel ? 0x01 : 0x00) << bit;
                                }
                            }
                            byte *= darknessFactor; // Adjust this factor for darkness level
                
                            imageData.append(byte);
                        }
                    }
                
                    // Send the image data
                    port->write(imageData);
                    write("\n"); // Print a newline to advance to the next line
                }
                
                

                MainWindow.CPP

                #include "mainwindow.h"
                #include "ui_mainwindow.h"
                #include <QImage>
                #include <iostream>
                #include "printer.h"
                #include <QDebug>
                #include <unistd.h>
                #include <QPainter>
                #include <QBuffer>
                #include <QPainter>
                MainWindow::MainWindow(QWidget *parent) :
                    QMainWindow(parent),
                    ui(new Ui::MainWindow)
                {
                    ui->setupUi(this);
                    
                }
                
                MainWindow::~MainWindow()
                {
                    delete ui;
                }
                
                QImage MainWindow::loadImage(const QString &filePath)
                {
                    QImage image(filePath);
                    if (image.isNull())
                    {
                        qDebug() << "Error loading image: " << filePath;
                    }
                    return image;
                }
                
                void MainWindow::on_pushButton_clicked()
                {
                    QApplication::processEvents();
                
                    Printer *printer = new Printer();
                    std::cout << "Trying to open port..." << std::endl;
                    bool res = printer->open("/dev/ttyS0");
                    std::cout << "Status: " << res << std::endl;
                    if (!res)
                    {
                        std::cerr << "Error opening port, aborting" << std::endl;
                        return;
                    }
                    QString imagePath = "/home/pi/git/Image_Print/Raspi.png"; // Replace with the path to your image
                
                    QImage image = loadImage(imagePath);
                
                    if (!image.isNull())
                    {
                        qDebug()<<"Image enter";
                
                        printer->write("Data");
                        printer->feed();
                        printer->feed();
                        printer->printImage(image);
                        printer->feed();
                        printer->feed();
                
                    }
                    else
                    {
                        qDebug() << "Image is null or invalid.";
                    }
                
                    printer->close();
                }
                
                

                Output:-

                Printed Image is below:-

                WhatsApp Image 2023-09-27 at 4.33.48 PM.jpeg

                Original Image is below:-

                Raspberry_Pi-Logo.wine.jpg

                SGaistS Offline
                SGaistS Offline
                SGaist
                Lifetime Qt Champion
                wrote on 27 Sept 2023, 19:05 last edited by
                #6

                Is it me or does it seems that your image is printed in "the wrong direction". It looks like you have things mirrored but per column.

                Interested in AI ? www.idiap.ch
                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                R 2 Replies Last reply 28 Sept 2023, 07:36
                0
                • SGaistS SGaist
                  27 Sept 2023, 19:05

                  Is it me or does it seems that your image is printed in "the wrong direction". It looks like you have things mirrored but per column.

                  R Offline
                  R Offline
                  Ramkumar Mohan
                  wrote on 28 Sept 2023, 07:36 last edited by
                  #7
                  This post is deleted!
                  1 Reply Last reply
                  0
                  • R Ramkumar Mohan has marked this topic as solved on 28 Sept 2023, 07:37
                  • R Ramkumar Mohan has marked this topic as unsolved on 28 Sept 2023, 07:38
                  • R Ramkumar Mohan has marked this topic as solved on 28 Sept 2023, 07:38
                  • SGaistS SGaist
                    27 Sept 2023, 19:05

                    Is it me or does it seems that your image is printed in "the wrong direction". It looks like you have things mirrored but per column.

                    R Offline
                    R Offline
                    Ramkumar Mohan
                    wrote on 28 Sept 2023, 07:42 last edited by
                    #8

                    @SGaist

                    MainWindow.CPP

                    #include "mainwindow.h"
                    #include "ui_mainwindow.h"
                    #include <QImage>
                    #include <iostream>
                    #include "printer.h"
                    #include <QDebug>
                    #include <unistd.h>
                    #include <QPainter>
                    #include <QBuffer>
                    #include <QPainter>
                    MainWindow::MainWindow(QWidget *parent) :
                        QMainWindow(parent),
                        ui(new Ui::MainWindow)
                    {
                        ui->setupUi(this);
                        
                    }
                    
                    MainWindow::~MainWindow()
                    {
                        delete ui;
                    }
                    
                    QImage MainWindow::loadImage(const QString &filePath)
                    {
                        QImage image(filePath);
                        if (image.isNull())
                        {
                            qDebug() << "Error loading image: " << filePath;
                        }
                        return image;
                    }
                    
                    void MainWindow::on_pushButton_clicked()
                    {
                        QApplication::processEvents();
                    
                        Printer *printer = new Printer();
                        std::cout << "Trying to open port..." << std::endl;
                        bool res = printer->open("/dev/ttyS0");
                        std::cout << "Status: " << res << std::endl;
                        if (!res)
                        {
                            std::cerr << "Error opening port, aborting" << std::endl;
                            return;
                        }
                    
                        QString imagePath = "/home/pi/git/Image_Print/Raspberry_Pi.jpg"; // Replace with the path to your image
                    
                        QImage image = loadImage(imagePath);
                    
                        if (!image.isNull())
                        {
                            qDebug()<<"Image enter";
                    
                            printer->write("Data");
                            printer->feed();
                            printer->feed();
                            printer->printImage(image);
                            printer->feed();
                            printer->feed();
                    
                        }
                        else
                        {
                            qDebug() << "Image is null or invalid.";
                        }
                    
                        printer->close();
                    }
                    
                    
                    

                    Printer.CPP

                    /*****************************************************************
                    * Thermal Printer Interface Library based on QT for the Rasp-Pi
                    * Based on the Arduino Library from Adafruit
                    * using QExtSerialPort
                    * Autor: Tobias Floery
                    * E-Mail: tobias@floery.net
                    ***************************************************************/
                    
                    #include "printer.h"
                    #include <QImage>
                    #include <iostream>
                    #include <unistd.h>
                    #include <QDebug>
                    #include <QPixmap>
                    Printer::Printer(QObject *parent) :
                        QObject(parent)
                    {
                    }
                    
                    // opens the serial port specified py path
                    
                    bool Printer::open(QString path) {
                    
                        port = new QextSerialPort(path);
                    
                        if (!port->open(QIODevice::WriteOnly))
                            return false;
                        // set options
                        port->setBaudRate(BAUD9600);
                        port->setDataBits(DATA_8);
                        port->setFlowControl(FLOW_OFF);
                        port->setParity(PAR_NONE);
                    
                        usleep(10000);
                        return true;
                    }
                    
                    // close the serial port
                    void Printer::close() {
                        port->close();
                    }
                    
                    // write single byte
                    void Printer::write(quint8 byte) {
                        port->write((const char*)&byte, 1);
                    }
                    
                    // write a string
                    void Printer::write(QString str)
                    {
                        port->write(str.toUtf8());
                    }
                    
                    void Printer::writes(char SOMETHING)
                    {
                        port->write(&SOMETHING);
                    }
                    
                    
                    // initialize the printer
                    void Printer::init() {
                        reset();
                        setStatus(true);
                        setControlParameter();
                        setPrintDensity();
                        setSleepTime();
                        setCodeTable();
                        setCharacterSet();
                        setBarcodePrintReadable();
                    }
                    
                    // reset the printer
                    void Printer::reset() {
                        write(27);
                        write(64);
                        usleep(50000);
                    }
                    
                    // sets the printer online (true) or ofline (false)
                    void Printer::setStatus(bool state) {
                        write(27);
                        write(61);
                        write(state);
                    }
                    
                    // set control parameters: heatingDots, heatingTime, heatingInterval
                    void Printer::setControlParameter(quint8 heatingDots, quint8 heatingTime, quint8 heatingInterval) {
                        write(27);
                        write(55);
                        write(heatingDots);
                        write(heatingTime);
                        write(heatingInterval);
                    }
                    
                    // set sleep Time in seconds, time after last print the printer should stay awake
                    void Printer::setSleepTime(quint8 seconds) {
                        write(27);
                        write(56);
                        write(seconds);
                        usleep(50000);
                        write(0xFF);
                    }
                    
                    // set double width mode: on=true, off=false
                    void Printer::setDoubleWidth(bool state) {
                        write(27);
                        write(state?14:20);
                    
                    }
                    
                    
                    // set the print density and break time
                    void Printer::setPrintDensity(quint8 printDensity, quint8 printBreakTime) {
                        write(18);
                        write(35);
                        write((printBreakTime << 5) | printDensity);
                    }
                    
                    // set the used character set
                    void Printer::setCharacterSet(CharacterSet set) {
                        write(27);
                        write(82);
                        write(set);
                    }
                    
                    // set the used code table
                    void Printer::setCodeTable(CodeTable table) {
                        write(27);
                        write(116);
                        write(table);
                    }
                    
                    // feed single line
                    void Printer::feed(void) {
                        write(10);
                    }
                    
                    // feed <<lines>> lines
                    void Printer::feed(quint8 lines) {
                        write(27);
                        write(74);
                        write(lines);
                    }
                    
                    // set line spacing
                    void Printer::setLineSpacing(quint8 spacing) {
                        write(27);
                        write(51);
                        write(spacing);
                    }
                    
                    // set Align Mode: LEFT, MIDDLE, RIGHT
                    void Printer::setAlign(AlignMode align) {
                        write(27);
                        write(97);
                        write(align);
                    }
                    
                    // set how many blanks should be kept on the left side
                    void Printer::setLeftBlankCharNums(quint8 space) {
                        if (space >= 47) space = 47;
                    
                        write(27);
                        write(66);
                        write(space);
                    }
                    
                    // set Bold Mode: on=true, off=false
                    void Printer::setBold(bool state) {
                        write(27);
                        write(32);
                        write((quint8) state);
                        write(27);
                        write(69);
                        write((quint8) state);
                    }
                    
                    // set Reverse printing Mode
                    void Printer::setReverse(bool state) {
                        write(29);
                        write(66);
                        write((quint8) state);
                    }
                    
                    // set Up/Down Mode
                    void Printer::setUpDown(bool state) {
                        write(27);
                        write(123);
                        write((quint8) state);
                    }
                    
                    // set Underline printing
                    void Printer::setUnderline(bool state) {
                        write(27);
                        write(45);
                        write((quint8) state);
                    }
                    
                    // enable / disable the key on the frontpanel
                    void Printer::setKeyPanel(bool state) {
                        write(27);
                        write(99);
                        write(53);
                        write((quint8) state);
                    }
                    
                    // where should a readable barcode code be printed
                    void Printer::setBarcodePrintReadable(PrintReadable n) {
                        write(29);
                        write(72);
                        write(n);
                    }
                    
                    // sets the height of the barcode in pixels
                    void Printer::setBarcodeHeight(quint8 height) {
                        if (height <= 1) height = 1;
                    
                        write(29);
                        write(104);
                        write(height);
                    }
                    
                    // sets the barcode line widths (only 2 or 3)
                    void Printer::setBarCodeWidth(quint8 width) {
                        if (width <= 2) width=2;
                        else if (width >= 3) width=3;
                    
                        write(29);
                        write(119);
                        write(width);
                    }
                    
                    // prints a barcode
                    void Printer::printBarcode(QString data, BarcodeType type) {
                        write(29);
                        write(107);
                        write(type);
                        write(data);
                        write(0);
                    }
                    
                    
                    bool Printer::isPrinterReady()
                    {
                        return port->isOpen() && port->isWritable();
                    }
                    
                    void Printer::printImage(const QImage &image)
                    {
                        if (!isPrinterReady())
                        {
                            qDebug() << "Printer is not ready.";
                            return;
                        }
                        qreal scaleFactor = 2.0; // Increase DPI by a factor of 2
                              qreal darknessFactor =1.0; // Adjust darkness level (experiment with this value)
                              // Scale the image for higher DPI (dots per inch)
                              QImage highDpiImage = image;
                    
                              // Disable device pixel ratio scaling (anti-aliasing)
                              highDpiImage.setDevicePixelRatio(1);
                    
                                  QImage monochromeImage = highDpiImage.convertToFormat(QImage::Format_Mono);
                              highDpiImage = monochromeImage.scaled(monochromeImage.width() * scaleFactor, monochromeImage.height() * scaleFactor, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                    
                        // Calculate the width of the image in bytes
                        int bytesPerLine = (monochromeImage.width() + 7) / 8;
                    
                        // Send the ESC/POS command to print the image
                        QByteArray printCommand;
                        printCommand.append(char(0x1D));  // ESC
                        printCommand.append(char(0x76));  // 'v'
                        printCommand.append(char(0x30));  // '0'
                        printCommand.append(char(0x00));  // Mode (0 for normal)
                    
                        // Append the image width and height
                        printCommand.append(char(bytesPerLine & 0xFF));
                        printCommand.append(char((bytesPerLine >> 8) & 0xFF));
                        printCommand.append(char(monochromeImage.height() & 0xFF));
                        printCommand.append(char((monochromeImage.height() >> 8) & 0xFF));
                    
                        // Send the print command
                        port->write(printCommand);
                    
                        // Send the image data
                        QByteArray imageData;
                        for (int y = 0; y < monochromeImage.height(); ++y)
                        {
                            for (int x = 0; x < bytesPerLine; ++x)
                            {
                                uchar byte = 0;
                                for (int bit = 0; bit < 8; ++bit)
                                {
                                    int pixelX = x * 8 + bit;
                                    if (pixelX < monochromeImage.width())
                                    {
                                        bool isBlackPixel = monochromeImage.pixel(pixelX, y) == qRgb(0, 0, 0);
                                        byte |= (isBlackPixel ? 0x01 : 0x00) << (7 - bit); // Corrected bit order
                    
                                    }
                                }
                                byte *= darknessFactor; // Adjust this factor for darkness level
                    
                                imageData.append(byte);
                            }
                        }
                    
                        // Send the image data
                        port->write(imageData);
                        write("\n"); // Print a newline to advance to the next line
                    }
                    
                    

                    I solved my issue with the above code.
                    Thanks ....

                    OUTPUT..

                    WhatsApp Image 2023-09-28 at 1.04.33 PM.jpeg

                    Original Image

                    Raspberry_Pi-Logo.wine.jpg

                    1 Reply Last reply
                    1

                    • Login

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • Users
                    • Groups
                    • Search
                    • Get Qt Extensions
                    • Unsolved