DEV Community

Shahzaib Rasool
Shahzaib Rasool

Posted on

Printing Images on an ESC/POS Thermal Printer in .NET MAUI

When working with POS systems, thermal printers are commonly used for printing receipts, logos, and QR codes. However, printing images on these printers in .NET MAUI can be slightly tricky because most thermal printers only support ESC/POS commands and monochrome images.

In this article, I’ll explain the workflow for printing images on an ESC/POS thermal printer using .NET MAUI.

The process generally involves four main steps.

  1. Load the image
  2. Convert the image to monochrome
  3. Convert the image to ESC/POS byte format
  4. Send the byte array to the printer

Step 1: Load the Image
First load the image from local storage.

public Bitmap LoadBitmap(string imagePath)
{
    return new Bitmap(imagePath);
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Convert Image to Monochrome
Thermal printers only support black and white printing, so the image needs to be converted to monochrome.

public Bitmap ConvertToMonochrome(Bitmap original)
{
    Bitmap mono = new Bitmap(original.Width, original.Height);

    for (int y = 0; y < original.Height; y++)
    {
        for (int x = 0; x < original.Width; x++)
        {
            Color pixel = original.GetPixel(x, y);
            int gray = (pixel.R + pixel.G + pixel.B) / 3;

            mono.SetPixel(x, y, gray < 128 ? Color.Black : Color.White);
        }
    }

    return mono;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Convert Image to ESC/POS Format
Thermal printers use ESC/POS commands to print images, so the bitmap must be converted to a byte array.


public byte[] GetImageBytes(Bitmap image)
{
    List<byte> bytes = new List<byte>();

    bytes.Add(0x1B);
    bytes.Add(0x2A);

    return bytes.ToArray();
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Send the Data to the Printer
Finally, send the byte array to the printer via Bluetooth, USB, or network connection.

public async Task PrintImage(byte[] data, Stream printerStream)
{
    await printerStream.WriteAsync(data, 0, data.Length);
}
Enter fullscreen mode Exit fullscreen mode

Summary

Printing images on ESC/POS thermal printers requires converting the image to monochrome and generating the appropriate ESC/POS commands before sending it to the printer.

Note: Most ESC/POS printers support commands like GS v 0 or ESC *. The image width should also match the printer width (usually 384px for 58mm printers or 576px for 80mm printers).

Top comments (0)